Question

So here is the code that throws the exception

    #region Header
            if (textBox2.Text != "")
            {
                try
                {
                    xmlTW.WriteStartElement("Header");
                    xmlTW.WriteRaw(Environment.NewLine);
                    xmlTW.WriteString(textBox2.Text);
                    xmlTW.WriteRaw(Environment.NewLine);
                    xmlTW.WriteEndElement();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            #endregion


            #region Body
            if (textBox3.Text != "")
            {
                try
                {
                    xmlTW.WriteStartElement("Rectangles");
                    xmlTW.WriteRaw(Environment.NewLine + textBox3.Text + Environment.NewLine);
                    xmlTW.WriteEndElement();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            #endregion

So, the problem is that the code will run smoothly only if one of the two textboxes is filled with data, if both of them contain text i get an invalid operation exception at WriteEndDocument();

I know it must be something simple, but i just can't figure it out :P . Any help is appreciated.

Thanks in advance.

Was it helpful?

Solution

Well-formed XML must have a Single root element. Following is well-formed XML:

<Header>
Some text
</Header>

It is well-formed because Header is root element there. However, following is not well-formed:

<Header>
Some text
</Header>
<Rectangles>
Some other text
</Rectangles>

To correct it, you got to put it in some root element.

<myRoot>
<Header>
Some text
</Header>
<Rectangles>
Some other text
</Rectangles>
</myRoot>

OTHER TIPS

You need to set the XmlWriterSettings ConformanceLevel to Fragment.

This will enable you keep the xml struct that you wanted without adding root element

var xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.ConformanceLevel = ConformanceLevel.Fragment;

and create you xml write like this:

XmlWriter xmlTW = XmlWriter.Create("myFile.xml", xmlWriterSettings)

This link can help you start working with XmlWriter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top