views:

52

answers:

2

Hi,

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!

+3  A: 

Your code is right, and you don't need to change how your ExceptionsList element is closed.

xmlWriter.WriteStartElement("ExceptionsList"); // ExceptionsList (Root) Element

xmlWriter.WriteStartElement("Exception"); // An Exception element
xmlWriter.WriteEndElement();

xmlWriter.WriteEndElement(); // End of ExceptionsList (Root) Element

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 XDocument instance, like this:

XDocument xml = new XDocument();
xml.Add(new XElement("Exception",
    new XElement("ExceptionType", "Exception"),
    new XElement("ExceptionMessage", 
        new XElement("InnerException", "innerException")),
    new XComment("some comment")));

xml.Save("sample2.xml");
Rubens Farias
Thanks Rubens! That did the trick! :)
Yustme
A: 

I believe the problem is here:

    new XElement("Exception Type", exceptionType),
     new XElement("Exception Message", exceptionMessage),

Neither Exception Type nor Exception Mesage is a valid name for an xml element. Then of course, if you use this (doomed) method to log the error... stack overflow.

Marc Gravell
Yes that's what caused the stackoverflow. I got ride of it. TBH, i never used spaces in xml tags. I don't know why i did this time :oThanks for your comment!
Yustme