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.
The error message is:
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:
You are Closing two elements there, but you open only one element (
<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.on last EndElement declaration use
instead of
writer.WriteEndElement();