I’m using xmlwriter to create an xml document. The xml document looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<ExceptionsList />
How can i prevent the /> and appropriately end the root node?
Because of this, i can’t append anything to the root node.
My code for creating the xml file looks like this:
string formatDate = DateTime.Now.ToString("d-MMM-yyyy");
XmlTextWriter xmlWriter = new XmlTextWriter(xmlfileName, Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 3;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("ExceptionsList"); // ExceptionsList (Root) Element
xmlWriter.WriteEndElement(); // End of ExceptionsList (Root) Element
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
And I append to the root node like this:
XDocument xml = XDocument.Load(xmlFileName);
XElement root = xml.Root;
root.Add(new XElement("Exception",
new XElement("Exception Type", exceptionType),
new XElement("Exception Message", exceptionMessage),
new XElement("InnerException", innerException),
new XElement("Comment", comment)));
xml.Save(xmlFileName);
This gives me a stackoverflow at runtime error too.
Any help would be appreciated.
Thanks in advance!
Your code is right, and you don’t need to change how your
ExceptionsListelement is closed.In your second snippet, you need to remove those white spaces from element name, as XML specification forbid that and add your elements into your
XDocumentinstance, like this: