以未知的元素顺序反序列化XML [英] Deserializing XML with unknown element order

查看:56
本文介绍了以未知的元素顺序反序列化XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为规格不足的服务实现客户端.尽管没有WSDL或等效文件,但它类似于SOAP.规范也没有提供有关元素正确顺序的任何信息-元素在规范中按字母顺序列出,但是如果请求中的元素顺序不正确,则服务会返回XML解析错误(该顺序由检查示例).

I'm trying to implement a client for a service with a really deficient spec. It's SOAP-like, although it has no WSDL or equivalent file. The spec also doesn't provide any information about the correct ordering of elements - they're listed alphabetically in the spec, but the service returns an XML parse error if they're out of order in the request (said order to be derived by examining the examples).

即使这很痛苦,我也可以使用来提交请求.但是,我不知道如何正确处理响应.

I can work with this for submitting requests, even if it's a pain. However, I don't know how to handle responses correctly.

同时使用 SoapEnvelope 和直接使用 XmlSerializer ,如果响应包含我尚未正确排序的元素,则显示为 null 在我的对象上.再次,我可以设法使用它,并使用以下命令手动订购类属性 Order 属性,但是我无法判断原始XML是否具有我未正确订购的字段,因此留为 null .

With both SoapEnvelope and directly with XmlSerializer, if the response contains an element I haven't yet ordered correctly, it shows up as null on my object. Once again, I can manage to work with this, and manually order the class properties with Order attributes, but I have no way to tell whether the original XML has a field that I didn't order correctly and thus got left as null.

这使我想到了当前的问题:如何检查XmlSerializer是否删除了字段?

This leads me to the current question: How can I check if the XmlSerializer dropped a field?

推荐答案

您可以使用

You can use the XmlSerializer.UnknownElement event on XmlSerializer to capture out-of-order elements. This will allow you to manually find and fix problems in deserialization.

一个更复杂的答案是在序列化时正确排序元素,而在反序列化时忽略顺序.这需要使用 XmlAttributes 类和 GetHashCode() for XmlAttributeOverrides .以下是一种可能的实现方式,该实现方式取决于预先了解所有需要其 XmlArrayAttribute.Order 属性被忽略,从而避免了创建复杂的自定义哈希方法:

A more complex answer would be to correctly order your elements when serializing, but ignore order when deserializing. This requires using the XmlAttributes class and the XmlSerializer(Type, XmlAttributeOverrides) constructor. Note that serializers constructed in this manner must be cached in a hash table and resused to avoid a severe memory leak, and thus this solution is a little "finicky" since Microsoft doesn't provide a meaningful GetHashCode() for XmlAttributeOverrides. The following is one possible implementation which depends upon knowing in advance all types that need their XmlElementAttribute.Order and XmlArrayAttribute.Order properties ignored, thus avoiding the need to create a complex custom hashing method:

public class XmlSerializerFactory : XmlOrderFreeSerializerFactory
{
    static readonly XmlSerializerFactory instance;

    // Use a static constructor for lazy initialization.
    private XmlSerializerFactory()
        : base(new[] { typeof(Type2), typeof(Type1), typeof(TestClass), typeof(Type3) }) // These are the types in your client for which Order needs to be ignored whend deserializing
    {
    }

    static XmlSerializerFactory()
    {
        instance = new XmlSerializerFactory();
    }

    public static XmlSerializerFactory Instance { get { return instance; } }
}

public abstract class XmlOrderFreeSerializerFactory
{
    readonly XmlAttributeOverrides overrides;
    readonly object locker = new object();
    readonly Dictionary<Type, XmlSerializer> serializers = new Dictionary<Type, XmlSerializer>();

    static void AddOverrideAttributes(Type type, XmlAttributeOverrides overrides)
    {
        if (type == null || type == typeof(object) || type.IsPrimitive || type == typeof(string))
            return;

        var mask = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public;
        foreach (var member in type.GetProperties(mask).Cast<MemberInfo>().Union(type.GetFields(mask)))
        {
            XmlAttributes overrideAttr = null;
            foreach (var attr in member.GetCustomAttributes<XmlElementAttribute>())
            {
                overrideAttr = overrideAttr ?? new XmlAttributes();
                overrideAttr.XmlElements.Add(new XmlElementAttribute { DataType = attr.DataType, ElementName = attr.ElementName, Form = attr.Form, IsNullable = attr.IsNullable, Namespace = attr.Namespace, Type = attr.Type });
            }
            foreach (var attr in member.GetCustomAttributes<XmlArrayAttribute>())
            {
                overrideAttr = overrideAttr ?? new XmlAttributes();
                overrideAttr.XmlArray = new XmlArrayAttribute { ElementName = attr.ElementName, Form = attr.Form, IsNullable = attr.IsNullable, Namespace = attr.Namespace };
            }
            if (overrideAttr != null)
                overrides.Add(type, member.Name, overrideAttr);
        }
    }

    protected XmlOrderFreeSerializerFactory(IEnumerable<Type> types)
    {
        overrides = new XmlAttributeOverrides();
        foreach (var type in types.SelectMany(t => t.BaseTypesAndSelf()).Distinct())
        {
            AddOverrideAttributes(type, overrides);
        }
    }

    public XmlSerializer GetSerializer(Type type)
    {
        if (type == null)
            throw new ArgumentNullException("type");
        lock (locker)
        {
            XmlSerializer serializer;
            if (!serializers.TryGetValue(type, out serializer))
                serializers[type] = serializer = new XmlSerializer(type, overrides);
            return serializer;
        }
    }
}

public static class TypeExtensions
{
    public static IEnumerable<Type> BaseTypesAndSelf(this Type type)
    {
        while (type != null)
        {
            yield return type;
            type = type.BaseType;
        }
    }
}

(注意-仅经过部分测试.)

(Note -- only partially tested.)

然后在反序列化类型时,使用工厂提供的 XmlSerializer .鉴于 SoapEnvelope XmlDocument 的子类,您应该能够按照

Then when deserializing a type, use the XmlSerializer provided by the factory. Given that SoapEnvelope is a subclass of XmlDocument, you should be able to deserialize the body node along the lines of the answer in Deserialize object property with StringReader vs XmlNodeReader.

这篇关于以未知的元素顺序反序列化XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆