在XML文件中写入时,名称字符错误无效

时间:2014-10-02 08:28:14

标签: c# xml

我正在尝试在XML文件中编写我的类。这是我的班级:

    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; } }
    }

这是我用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();
        }

但它引发了这个错误:

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

尝试运行此行:

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

谁能告诉我如何修复它?感谢

1 个答案:

答案 0 :(得分:1)

您正在尝试编写在属性值中定义名称的元素。 WriteElementString采用元素的名称,后跟值。

而不是:

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

这样做:

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

另一种方法是使用框架自动创建类的XML表示。 StackOverflow上有很多可用的例子。例如Serialize an object to XML