Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing XML in C# - 'Token StartElement in state Epilog would result in an invalid XML document' error

Tags:

c#

xml

I'm trying to write to an XML document, taking data from an ArrayList of lists

        for (int i = 0; i < 15; i++)
        {
            string headname = (headers[0] as List<string>)[i];
                headname.Replace("&", "&amp;");
                headname.Replace("<", "&lt;");
                headname.Replace(">", "&gt;");
                headname.Replace("\"", "&quot;");
                headname.Replace("'", "&apos;");
            textWriter.WriteStartElement("MetadataName", "");
            textWriter.WriteString(headname);
            textWriter.WriteEndElement();

The problem I'm having is that after it goes through the for loop once, i get a 'Token StartElement in state Epilog would result in an invalid XML document' error on the line with WriteStartElement, and I've tried looking up how to fix it and have not really had any breakthroughs. Thanks.

EDITED for update.

like image 349
omicronlyrae Avatar asked Jul 20 '10 09:07

omicronlyrae


2 Answers

An XML document will have a root element ie one that includes all other elements. You don't have one

Your doc is like

<MetadataName><header0/><header1/></MetadataName>
<MetadataName><header0/><header1/></MetadataName>

An XML doc is like

<root>
    <MetadataName><header0/><header1/></MetadataName>
    <MetadataName><header0/><header1/></MetadataName>
</root>

You need to WriteStartElement and WriteEndElement around your loop

like image 195
mmmmmm Avatar answered Oct 13 '22 18:10

mmmmmm


Your problem is here:

textWriter.WriteStartElement("Metadata Name", "");

An element name cannot contain spaces. Try this:

textWriter.WriteStartElement("MetadataName", "");

I am assuming that the data in your headers array is well formed for XML (for example, all & are escaped to &amp; etc...).

Additionally, as Mark notes in his answer, you need to make sure the XML is rooted - that is, that there is a root element in which you put your MetadataName elements.

Read about well formed XML and what that means - you need to make sure your document is well formed, as you build it up.

like image 43
Oded Avatar answered Oct 13 '22 17:10

Oded