csharp .NET Xml序列化扩展

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp .NET Xml序列化扩展相关的知识,希望对你有一定的参考价值。

using System;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;


public static class XNodeSerializationExtensions
{
    static string GetXmlRootName(XNode xml)
    {
        return (xml as XDocument)?.Root?.Name.LocalName
            ?? (xml as XElement)?.Name.LocalName;
    }

    public static T Deserialize<T>(this XNode xml, XmlSerializer serializer = null, XmlDeserializationEvents? events = null)
    {
        //We need XmlRootAttribute. Why? See here http://stackoverflow.com/a/4761975/508797
        var rootName = GetXmlRootName(xml);

        var deserializer = serializer ??
            (rootName != null
            ? new XmlSerializer(typeof(T), new XmlRootAttribute(rootName))
            : new XmlSerializer(typeof(T))
            )
            ;

        using (var rdr = xml.CreateReader())
        {
            if (events != null)
                return (T)deserializer.Deserialize(rdr, events.Value);
            else
                return (T)deserializer.Deserialize(rdr);
        }
    }

    public static T TryDeserialize<T>(this XNode xml, XmlSerializer serializer = null, XmlDeserializationEvents? events = null, Func<XNode, T> ifFails = null)
    {
        var rootName = GetXmlRootName(xml);
        var deserializer = serializer ??
            (rootName != null
            ? new XmlSerializer(typeof(T), new XmlRootAttribute(rootName))
            : new XmlSerializer(typeof(T))
            )
            ;

        using (var rdr = xml.CreateReader())
        {
            if (!deserializer.CanDeserialize(rdr))
                return ifFails == null ? default(T) : ifFails(xml);
            if (events != null)
                return (T)deserializer.Deserialize(rdr, events.Value);
            else
                return (T)deserializer.Deserialize(rdr);
        }

    }


    static XDocument Serialize<T>(T obj, XmlSerializer serializer = null, bool omitNamespaces = true)
    {
        serializer = serializer ?? new XmlSerializer(typeof(T));

        var newXml = new XDocument();
        using (var xml = newXml.CreateWriter())
        {
            serializer.Serialize(xml, obj, omitNamespaces ? new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }) : null);

        }

        return newXml;
    }

    /// <summary>
    /// Serializes object to Xml and replace current xml node with new generated xml
    /// </summary>
    /// <typeparam name="TXNode"></typeparam>
    /// <typeparam name="T"></typeparam>
    /// <param name="xml"></param>
    /// <param name="obj"></param>
    /// <param name="serializer"></param>
    /// <param name="omitNamespaces"></param>
    /// <returns></returns>
    public static TXNode Serialize<TXNode, T>(this TXNode xml, T obj, XmlSerializer serializer = null) where TXNode : XNode
    {
        var newXmlDoc = Serialize(obj, serializer);
        var newElement = newXmlDoc.Root;

        if (!(xml is XDocument))
        {
            xml.ReplaceWith(newElement);
            return newElement as TXNode;
        }

        var xmlDoc = xml as XDocument;

        if (xmlDoc == null)
            throw new NotSupportedException("Unexpected XNode type - expected XDocument");

        xmlDoc.RemoveNodes();//For XDocument with existing content writing works only if RemoveNodes was executed prior
        using (var wr = xmlDoc.CreateWriter())
        {
            newXmlDoc.Root.WriteTo(wr);
            return xml;
        }
    }
}

以上是关于csharp .NET Xml序列化扩展的主要内容,如果未能解决你的问题,请参考以下文章

csharp xml序列化

csharp 序列化XML,将XMLfeed转换为模型

csharp XML扩展类

csharp 使用适当的缩进来扩展您的xml文档的扩展

csharp 此类演示了将对象序列化和反序列化为xml字符串的方法

csharp protobuf-net / MessagePack / Json.NET序列化测试