How to deserialize an element as an XmlNode?
- by mackenir
When using Xml serialization in C#, I want to deserialize a part of my input XML to an XmlNode.
So, given this XML:
<Thing Name="George">
<Document>
<subnode1/>
<subnode2/>
</Document>
</Thing>
I want to deserialize the Document element to an XmlNode.
Below is my attempt which given the XML above, sets Document to the 'subnode1' element rather than the 'Document' element.
How would I get the code to set the Document property to the Document element?
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
[Serializable]
public class Thing
{
[XmlAttribute] public string Name {get;set;}
public XmlNode Document { get; set; }
}
class Program
{
static void Main()
{
const string xml = @"
<Thing Name=""George"">
<Document>
<subnode1/>
<subnode2/>
</Document>
</Thing>";
var s = new XmlSerializer(typeof(Thing));
var thing = s.Deserialize(new StringReader(xml)) as Thing;
}
}
However, when I use an XmlSerializer to deserialize the XML above to an instance of Thing, the Document property contains the child element 'subnode1', rather than the 'doc' element.
How can I get the XmlSerializer to set Document to an XmlNode containing the 'doc' element.