XMLSerializer to XElement

放肆的年华 提交于 2019-12-03 05:26:59

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);
}
Timothy

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;
}

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!