17

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!

Community
  • 1
  • 1
silent
  • 14,494
  • 4
  • 46
  • 86
  • Can you clarify exactly what you are thinking might constitute a `nicer` / `cleaner` way? – Chris Walsh Feb 02 '15 at 17:41
  • 1
    well, something that maybe does not involve to create/open two different readers and using the InnerXml (string)? – silent Feb 02 '15 at 17:44
  • This is what methods and extension methods are for, if you're doing a lot of the same code, extract to a function... That code looks pretty concise to me; so probably be more specific. – Greg B Feb 02 '15 at 18:07
  • Maybe there really is no "nicer" solution - but that's what I like to find out here ;-) – silent Feb 02 '15 at 18:13

3 Answers3

23

If you already have a XmlDocument object than you could use XmlNodeReader

MyClass response = null;
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
using (XmlReader reader = new XmlNodeReader(aciResponse.Data))
{
    response = (MyClass)serializer.Deserialize(reader);
}
Artem Popov
  • 368
  • 2
  • 7
19

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;
}
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
  • 1
    Well, that's at least a bit shorter solution :) I'll wait, however, if there might be more suggestions. – silent Feb 02 '15 at 18:21
13

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.

Andreas
  • 5,393
  • 9
  • 44
  • 53
ViBi
  • 515
  • 7
  • 19