Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving xml file and ConformanceLevel

Tags:

c#

.net

xml

I have method which should save list of objects into xml file

 private void DumpToXMLFile(List<Url> urls, string fileName)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;
            settings.NewLineOnAttributes = true;
            settings.ConformanceLevel = ConformanceLevel.Auto;

            using (XmlWriter writer = XmlWriter.Create(fileName, settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Countries");
                foreach (var url in urls)
                {
                    writer.WriteStartElement("Country");
                        writer.WriteElementString("Name", url.Name);                        
                        writer.WriteElementString("Url", url.Uri);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.WriteEndElement();                
            }
        }

I;m getting this expcetion:

An unhandled exception of type 'System.InvalidOperationException' occurred in ...

Additional information: Token EndElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.

Tried with ConformanceLevel.Fragment but than I'm getting exception that I should use ConformanceLevel.Auto if I want to save xml file.

like image 826
user1765862 Avatar asked Dec 16 '25 18:12

user1765862


2 Answers

The error message is:

Token EndElement in state EndRootElement would result in an invalid XML document.

In other words, you are trying to write an end element when there is nothing else to close (you have already arrived at the document root).

Hence, look at where you close any elements:

writer.WriteEndElement();
writer.WriteEndElement();

You are Closing two elements there, but you open only one element (<Countries>):

writer.WriteStartDocument();
writer.WriteStartElement("Countries");

WriteStartDocument does not start an Xml element, it just writes the document Xml declaration (e.g. <?xml version="1.0" encoding="UTF-8"?>).

Remove the second writer.WriteEndElement(); and you should be fine.

like image 187
O. R. Mapper Avatar answered Dec 19 '25 10:12

O. R. Mapper


on last EndElement declaration use

 writer.WriteEndDocument();  

instead of writer.WriteEndElement();

like image 25
BobRock Avatar answered Dec 19 '25 10:12

BobRock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!