Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLSerializer to XElement

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...

like image 743
user883434 Avatar asked Oct 27 '11 09:10

user883434


3 Answers

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);
}
like image 145
Stecya Avatar answered Oct 18 '22 05:10

Stecya


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;
}
like image 43
Timothy Avatar answered Oct 18 '22 06:10

Timothy


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.

like image 39
John Saunders Avatar answered Oct 18 '22 05:10

John Saunders