0

I'm trying to write my class in XML file. Here's my Class:

    class Version
    {
        string _version;
        bool _showNextTime;
        public Version(string version, bool showNextTime)
        {
            this._version = version;
            this._showNextTime = showNextTime;
        }

        public string LastVersion { get { return _version; } }
        public bool ShowNextTime { get { return _showNextTime; } }
    }

And this is my code to write in XML:

        Version newVersion = new Version("3.0.1", false);
        using (XmlWriter writer = XmlWriter.Create("Versions.xml"))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("Version");
            writer.WriteElementString(newVersion.LastVersion, newVersion.ShowNextTime.ToString());
            writer.WriteEndElement();
            writer.WriteEndDocument();
        }

But it throws this error:

Invalid name character in '3.0.1'. The '3' character, hexadecimal value 0x33, cannot be included in a name.

Trying to run this line:

 writer.WriteElementString(newVersion.LastVersion, newVersion.ShowNextTime.ToString());

Can anyone tell me how to fix it? Thanks

Ghasem
  • 14,455
  • 21
  • 138
  • 171

1 Answers1

1

You are trying to write elements with names defined in the property value. WriteElementString takes the name of the element followed by the value.

Instead of this:

 writer.WriteElementString(
     newVersion.LastVersion, 
     newVersion.ShowNextTime.ToString());

Do this:

 writer.WriteElementString("LatestVersion", newVersion.LastVersion);
 writer.WriteElementString("ShowNextTime", newVersion.ShowNextTime.ToString());

An alternative method is to use the framework create the XML representation of your class automatically. There are many examples of that available on StackOverflow. For example Serialize an object to XML

Community
  • 1
  • 1
DavidG
  • 113,891
  • 12
  • 217
  • 223