saving xml file and ConformanceLevel

2019-07-27 06:00发布

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.

标签: c# .net xml
2条回答
Explosion°爆炸
2楼-- · 2019-07-27 06:45

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.

查看更多
We Are One
3楼-- · 2019-07-27 06:48

on last EndElement declaration use

 writer.WriteEndDocument();  

instead of writer.WriteEndElement();

查看更多
登录 后发表回答