Fermin
Fermin

Reputation: 36111

Decoding values stored in XDocument

I have created an XDocument object containing some exception data, I want to save this to an XML file so that it can be reviewed when investigating errors:

XDocument xmlDoc = XDocument.Parse(myCustomObject.SerializeToXml());

I've using the Save() method to save this data to file:

xmlDoc.Save(@"C:\myFile.xml", SaveOptions.None);

One of the nodes is output containing escaped characters (< and >), for example

<RootNode>
  <Name>My Object</Name>
  <DiagnosticInfo>
    &lt;DiagnosticInfo&gt;
      &lt;Processors&gt;
        &lt;String&gt;
          Something Something
        &lt;String&gt;
      &lt;/Processors&gt;
    &lt;/DiagnosticInfo&gt;
  </DiagnosticInfo>
</RootNode>

I've tried calling HttpUtility.DecodeHtml() on the "DiagnosticInfo" XElement but it is always output as escaped, any way round this? Do I have to do something to the DiagnosticInfo element to tell it not to treat its content as a string?

The DiagnosticInfo element is the one that would be most useful so I'd like to have it looking proper when the XML file is opened.

Edit In response to Jon Skeet's comment:

public string SerializeToXml()
{
    XmlSerializer s = new XmlSerializer(GetType());

    using (StringWriter w = new StringWriter())
    {
        s.Serialize(w, this);
        return w.ToString();
    }
}

Upvotes: 2

Views: 493

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93601

.Net serialisation uses reflection to decide what XML Elements to generate. These are based on the property names (like Name, DiagnosticInfo).

You mention DiagnosticInfo is an XElement. That means it is not a hierarchy of other objects, which is what you wanted, but rather it is a parser of XML elements and actually stores its XML as a string. When you serialise it you just get a single content value as a string.

You either need to parse/de-serialize your "info" into a more complex structure that actually contains properties like "Processors", or write out the XML manually using an XmlTextWriter and .WriteStartElement(), WriteEndElement() etc

Writing it out manually, rather than trying to serialize it, is quite easy and would be my choice. The only unusual method you will need is XmlTextWriter.WriteRaw which will stream out your raw XML in the middle of your other writes.

Upvotes: 1

Related Questions