16

I have been working with XML in database LINQ and find that it is very difficult to work with the serializer.

The database LINQ required a field that store XElement.

I have a complex object with many customized structure class, so I would like to use the XmlSerializer to serialize the object.

However, the serializer can only serialize to file ("C:\xxx\xxx.xml") or a memory stream.

However to convert or serialize it to be a XElement so that I can store in the database using LINQ?

And How to do the reverse? i.e. Deserialize an XElement...

0

4 Answers 4

14

Try to use this

using (var stream = new MemoryStream())
{
    serializer.Serialize(stream, value);
    stream.Position = 0;

    using (XmlReader reader = XmlReader.Create(stream))
    {
        XElement element = XElement.Load(reader);
    }
}

deserialize :

XmlSerializer xs = new XmlSerializer(typeof(XElement));
using (MemoryStream ms = new MemoryStream())
{
     xs.Serialize(ms, xml);
     ms.Position = 0;

     xs = new XmlSerializer(typeof(YourType));
     object obj = xs.Deserialize(ms);
}
2
  • 1
    Thanks! This seems like it should be easier than it is.
    – bnieland
    Nov 7, 2011 at 14:47
  • While this would work, the answer by @Timothy is much better.
    – Seth
    Nov 16, 2015 at 3:20
12

To make what John Saunders was describing more explicit, deserialization is very straightforward:

public static object DeserializeFromXElement(XElement element, Type t)
{
    using (XmlReader reader = element.CreateReader())
    {
        XmlSerializer serializer = new XmlSerializer(t);
        return serializer.Deserialize(reader);
    }
}

Serialization is a little messier because calling CreateWriter() from an XElement or XDocument creates child elements. (In addition, the XmlWriter created from an XElement has ConformanceLevel.Fragment, which causes XmlSerialize to fail unless you use the workaround here.) As a result, I use an XDocument, since this requires a single element, and gets us around the XmlWriter issue:

public static XElement SerializeToXElement(object o)
{
    var doc = new XDocument();
    using (XmlWriter writer = doc.CreateWriter())
    {
        XmlSerializer serializer = new XmlSerializer(o.GetType());
        serializer.Serialize(writer, o);
    }

    return doc.Root;
}
4

First of all, see Serialize Method to see that the serializer can handle alot more than just memory streams or files.

Second, try using XElement.CreateWriter and then passing the resulting XmlWriter to the serializer.

3
-1

The SQL has XML data type may be this can help you look at msdn

1
  • How will that help with serialization or XElement? Oct 27, 2011 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.