Search code examples
c#xmlxmlwriter

Invalid XML when using XmlWriter in C#


I am trying to create the following XML document-

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();

However on debugging I getback this error -

Token StartAttribute in state Element Content would result in an invalid XML document.

On the line - w.WriteAttributeString("Name", textBox1.Text);

I have checked for spaces etc however not sure why this is cropping up, any help is appreciated.


Solution

  • The call to w.WriteStartElement("Person"); should be part of the loop.

    After all, you call w.WriteEndElement() in the loop as well.