在c#中使用XmlWriter时无效的XML

本文关键字:无效 XML XmlWriter | 更新日期: 2023-09-27 18:16:03

我正在尝试创建以下XML文档-

FileStream fs = new FileStream(path, FileMode.Create);
            XmlWriter w = XmlWriter.Create(fs);
            w.WriteStartDocument();
            w.WriteStartElement("People");
            w.WriteStartElement("Person");
            // loop over checked elements
            foreach (var xxx in checkedListBox1.Items)
            {
                w.WriteAttributeString("Name", textBox1.Text);
                w.WriteAttributeString("GamerTag", textBox2.Text);
                w.WriteAttributeString("Wins", textBox3.Text);
                w.WriteAttributeString("Losses", textBox4.Text);
                w.WriteAttributeString("Ratio", textBox5.Text);
                // get id of this match
                id = checkedListBox1.Text.Substring(1, 3);
                // call the function at the service to download the type of struct we require
                res = client.photo(id);
                format = System.Drawing.Imaging.ImageFormat.Jpeg;
                w.WriteElementString("Picture-id", res.ToString());
                if (checkedListBox1.GetItemChecked(checkedListBox1.SelectedIndex))
                {
                    // do something
                    w.WriteElementString("Game", checkedListBox1.Text);
                }
                w.WriteEndElement();
            }
            w.WriteEndElement();
            w.WriteEndDocument();
            w.Flush();
            fs.Close();

但是在调试时我得到这个错误-

状态元素内容中的Token StartAttribute将导致无效的XML文档。

在线- w.WriteAttributeString("Name", textBox1.Text);

我已经检查了空格等,但不确定为什么会出现这种情况,任何帮助都是感激的。

在c#中使用XmlWriter时无效的XML

w.WriteStartElement("Person");的调用应该是循环的一部分。

毕竟,在循环中也调用了w.WriteEndElement()

正如Tomalak指出的那样,w.WriteStartElement("Person");应该是循环的一部分。除此之外,在GUI中动态创建XML不是nice。您应该考虑构建单独的类来保存您的数据结构。

class Person 
{
    public string Name { get; set; }
    public string GamerTag { get; set; }
    // all other attributes go here
}
class People 
{
    public Person[] Persons { get; setM }
}

手动填充这些类或将它们绑定到控件并从这些类生成XML。还要考虑更改控件的名称。知道控件代表什么总是好的,而不是先在表单中找到它。textBox1不是很有意义,NameTextBox是更好的选择,你不觉得吗?

我认为w.WriteStartElement("Person");行必须写在循环中。循环中的元素不是开始的,而是结束的