Better IXmlSerializable format?

旧城冷巷雨未停 提交于 2019-11-28 14:35:18

You can use [XmlAnyElement] to add an XElement []-valued property to your class that handles serialization and deserialization of properties that cannot be automatically serialized, like so:

[XmlRoot(Namespace = JobInput.XmlNamespace)]
[XmlType(Namespace = JobInput.XmlNamespace)]
public class JobInput
{
    const string XmlNamespace = "";

    public int AgencyId { get; set; }
    public Guid ExternalId { get; set; }
    public string Requester { get; set; }

    [XmlIgnore]
    public IInput Input { get; set; }

    [XmlAnyElement]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public XElement[] XmlCustomElements
    {
        get
        {
            var list = new List<XElement>();
            if (Input != null)
                list.Add(Input.SerializePolymorphicToXElement(XName.Get("Input", XmlNamespace)));
            // Add others as needed.
            return list.ToArray();
        }
        set
        {
            if (value == null)
                return;
            this.Input = value.DeserializePolymorphicEntry<IInput>(XName.Get("Input", XmlNamespace));
            // Add others as needed.
        }
    }
}

Your standard properties will now get automatically serialized and your custom properties can be semi-automatically serialized through nested calls to XmlSerializer using the appropriate type. The following extension methods are required:

public static class XObjectExtensions
{
    public static XmlSerializerNamespaces NoStandardXmlNamespaces()
    {
        var ns = new XmlSerializerNamespaces();
        ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
        return ns;
    }

    public static object Deserialize(this XContainer element, Type type, XmlSerializer serializer)
    {
        using (var reader = element.CreateReader())
        {
            return (serializer ?? new XmlSerializer(type)).Deserialize(reader);
        }
    }

    public static XElement SerializeToXElement<T>(this T obj, XmlSerializerNamespaces ns, XmlSerializer serializer)
    {
        var doc = new XDocument();
        using (var writer = doc.CreateWriter())
            (serializer ?? new XmlSerializer(obj.GetType())).Serialize(writer, obj, ns);
        var element = doc.Root;
        if (element != null)
            element.Remove();
        return element;
    }

    const string TypeAttributeName = "AssemblyQualifiedName";

    public static T DeserializePolymorphicEntry<T>(this XElement[] arrayValue, XName name)
    {
        var element = arrayValue.Where(e => e.Name == name).FirstOrDefault();
        return element.DeserializePolymorphic<T>(name);
    }

    public static T DeserializePolymorphic<T>(this XElement value, XName name)
    {
        if (value == null)
            return default(T);
        var typeName = (string)value.Attribute(TypeAttributeName);
        if (typeName == null)
            throw new InvalidOperationException(string.Format("Missing AssemblyQualifiedName for \"{0}\"", value.ToString()));
        var type = Type.GetType(typeName, true); // Throw on error
        return (T)value.Deserialize(type, XmlSerializerFactory.Create(type, name));
    }

    public static XElement SerializePolymorphicToXElement<T>(this T obj, XName name)
    {
        if (obj == null)
            return null;
        var element = obj.SerializeToXElement(XObjectExtensions.NoStandardXmlNamespaces(), XmlSerializerFactory.Create(obj.GetType(), name));
        // Remove namespace attributes (they will be added back by the XmlWriter if needed)
        foreach (var attr in element.Attributes().Where(a => a.IsNamespaceDeclaration).ToList())
            attr.Remove();
        element.Add(new XAttribute("AssemblyQualifiedName", obj.GetType().AssemblyQualifiedName));
        return element;
    }
}

public static class XmlSerializerFactory
{
    static readonly object padlock;
    static readonly Dictionary<Tuple<Type, XName>, XmlSerializer> serializers;

    // An explicit static constructor enables fairly lazy initialization.
    static XmlSerializerFactory()
    {
        padlock = new object();
        serializers = new Dictionary<Tuple<Type, XName>, XmlSerializer>();
    }

    /// <summary>
    /// Return a cached XmlSerializer for the given type and root name.
    /// </summary>
    /// <param name="type"></param>
    /// <param name="name"></param>
    /// <returns>a cached XmlSerializer</returns>
    public static XmlSerializer Create(Type type, XName name)
    {
        // According to https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx
        // XmlSerializers created with new XmlSerializer(Type, XmlRootAttribute) must be cached in a hash table 
        // to avoid a severe memory leak & performance hit.
        if (type == null)
            throw new ArgumentNullException();
        if (name == null)
            return new XmlSerializer(type);
        lock (padlock)
        {
            XmlSerializer serializer;
            var key = Tuple.Create(type, name);
            if (!serializers.TryGetValue(key, out serializer))
                serializers[key] = serializer = new XmlSerializer(type, new XmlRootAttribute { ElementName = name.LocalName, Namespace = name.NamespaceName });
            return serializer;
        }
    }
}

Doing it this way makes your class look simpler and reduces the possibility of bugs from mistakes in implementing IXmlSerializable - but it does require a little bit of reusable infrastructure.

Prototype fiddle.

Seems what I was after was possible

public void GenericWriter<T>(ref XmlWriter writer, string propertyName, T property)
{
    writer.WriteStartElement(propertyName);
    var xmlSerializer = new XmlSerializer(typeof(T));
    xmlSerializer.Serialize(writer, property);
    writer.WriteEndElement();
}

so same for reader. I ended up using ref just in case.

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