Reputation: 16128
I am looking for a clean and short way to deserialize a XmlDocument
object. The closest thing I found was this but I am really wondering if there is no nicer way to do this (in .NET 4.5 or even 4.6) since I already have the XmlDocument.
So currently this looks as follows:
// aciResponse.Data is a XmlDocument
MyClass response;
using (XmlReader reader = XmlReader.Create((new StringReader(aciResponse.Data.InnerXml))))
{
var serializer = new XmlSerializer(typeof(MyClass));
response = (MyClass)serializer.Deserialize(reader);
}
Thanks for any better idea!
Upvotes: 20
Views: 40150
Reputation: 378
If you already have a XmlDocument
object than you could use XmlNodeReader
MyClass response = null;
using (XmlReader reader = new XmlNodeReader(aciResponse.Data))
{
var serializer = new XmlSerializer(typeof(MyClass));
response = (MyClass)serializer.Deserialize(reader);
}
Upvotes: 24
Reputation: 627
There is a better and lazy way to do this. But it is possible only if you are using Visual Studio.
Steps:
Done. Visual Studio will generate all the class definitions required to de-serialize this XML.
Upvotes: 13
Reputation: 49978
You could forgo the XmlReader
and use a TextReader
instead and use the TextReader
XmlSerializer.Deserialize Method
overload.
Working example:
void Main()
{
String aciResponseData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><tag><bar>test</bar></tag>";
using(TextReader sr = new StringReader(aciResponseData))
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyClass));
MyClass response = (MyClass)serializer.Deserialize(sr);
Console.WriteLine(response.bar);
}
}
[System.Xml.Serialization.XmlRoot("tag")]
public class MyClass
{
public String bar;
}
Upvotes: 21