tags:

views:

584

answers:

3

I would like to invoke XmlSerializer.Deserialize passing it an XDocument. It can take a Stream, an XmlReader or a TextReader.

Can I generate one of the above from XDocument without actually dumping the XDocument into some intermediate store, such as a MemoryStream?

It seems that what I'm after is an implementation of XmlReader that works with an XDocument. I can't find one though.

+11  A: 

You can use XDocument.CreateReader() to create an XmlReader that reads the contents of the XDocument.

Equivalently, the following will work too.

XmlReader GetReader(XDocument doc)
{
    return doc.Root.CreateReader();
}
Steve Guidi
I didn't know about this method... much better than my own answer ;)
Thomas Levesque
It does indeed work in 3.5. Perfect!
romkyns
This works in .NET 3.5. Jeff Yates updated the link.
John Saunders
Thank you for updating!
Steve Guidi
A: 

Just thought I should add that after the XmlReader is created, i.e.:

XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
XmlReader reader = xmlDocumentToDeserialize.CreateReader();

then you should call:

reader.MoveToContent();

because otherwise the reader will not "point" to the first node, causing the appearance of an empty reader! Then you can safely call Deserialize:

MyObject myObject = (MyObject)serializer.Deserialize(reader);
dotNetkow
A: 

Here's a utility to serialize and deserialize objects to/from XDocument.

XDocument doc = SerializationUtil.Serialize(foo);
Foo foo = SerializationUtil.Deserialize<Foo>(doc);

Here's the class:

public static class SerializationUtil
{
    public static T Deserialize<T>(XDocument doc)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

        using (var reader = doc.Root.CreateReader())
        {
            return (T)xmlSerializer.Deserialize(reader);
        }
    }

    public static XDocument Serialize<T>(T value)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

        XDocument doc = new XDocument();
        using (var writer = doc.CreateWriter())
        {
            xmlSerializer.Serialize(writer, value);
        }

        return doc;
    }
}
Simon_Weaver