silent
silent

Reputation: 16128

Shortest way to deserialize XmlDocument

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

Answers (3)

Artem Popov
Artem Popov

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

ViBi
ViBi

Reputation: 627

There is a better and lazy way to do this. But it is possible only if you are using Visual Studio.

Steps:

  1. Open Visual Studio and create a new class file (say Sample1.cs). Now remove the sample class definition from this class file.
  2. Copy your XML file into the clipboard (Ctrl+A, Ctrl+C)
  3. In Visual Studio, go to Edit menu and select "Paste Special"->"Paste XML as Classes".

Done. Visual Studio will generate all the class definitions required to de-serialize this XML.

Upvotes: 13

SwDevMan81
SwDevMan81

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

Related Questions