用未知字段反序列化XML-会发生什么? [英] Deserializing XML with unknown fields - what will happen?

查看:55
本文介绍了用未知字段反序列化XML-会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们开发了一个使用XML与Microsoft Dynamics AX对话"的应用程序.不幸的是,没有记录XML格式,但是在我之前从事该项目工作的人只是从文件中提取了XSD架构,当从AX反序列化数据时,我们对此进行了验证.

We have developed an application that "talks" to Microsoft Dynamics AX using XML. Unfortunately, the XML format isn't documented, but the guy working on the project before me simply extracted an XSD schema from the files, which we validate against when deserializing data from AX.

我们现在唯一的问题是,客户端经常在AX中添加新字段-这自然会破坏架构.他们希望我们完全关闭验证(我们不想在每次添加新字段来尝试某些事情时都依赖您!"),我强烈建议不要这样做.

The only problem we have now, is that the client frequently adds new fields in AX - which naturally breaks the schema. They want us to turn off validation altogether ("We don't want to be dependent on you every time we add a new field to try something out!"), which I have advised strongly against.

但是真的会有负面后果吗?即,只要仅添加新值,XmlSerializer会实际上搞乱现有值吗?我发现几乎不可能测试所有假设的场景,这就是为什么我要在这里询问...

But could there really be negative consequences? I.e., would the XmlSerializer actually mess up existing values, as long as only new values are added? I find it pretty much impossible to test all hypothetical scenarios, which is why I'm asking here...

一个具体的例子是这样的格式:

A concrete example would be a format like this:

<Root>
    <A>Foo</A>
    <B>1234</B>
</Root>

现在假设他们像这样添加新字段,但不要删除现有值:

Suppose now they add new fields like this, but don't remove existing values:

<Root>
    <A>Foo</A>
    <C>9876</C>
    <B>1234</B>
    <D>Bar</D>
</Root>

尽管如此(在此变体或其他变体中),我们仍然能够正确解析A和B吗?

Would we be able to parse A and B correctly nonetheless (in this or other variants)?

谢谢.

推荐答案

尝试以下方法.

定义您的班级,如下所示.对于每个未知字段,请创建字典.请注意 XmlIgnore 属性.

Define your class as follows. For each unknown field make the dictionary. Note the XmlIgnore attribute.

public class Root
{
    public string A { get; set; }
    public int B { get; set; }

    [XmlIgnore]
    public Dictionary<string, string> Dict { get; set; }
}

订阅 UnknownElement 事件.

var xs = new XmlSerializer(typeof(Root));
xs.UnknownElement += Xs_UnknownElement;

在事件处理程序中,我们手动从未知元素中读取数据并将其放入字典中.

In the event handler we manually read the data from the unknown elements and put it in the dictionary.

private static void Xs_UnknownElement(object sender, XmlElementEventArgs e)
{
    var root = (Root)e.ObjectBeingDeserialized;

    if (root.Dict == null)
        root.Dict = new Dictionary<string, string>();

    root.Dict.Add(e.Element.Name, e.Element.InnerText);
}

反序列化照常进行:

Root root;

using (var stream = new FileStream("test.xml", FileMode.Open))
    root = (Root)xs.Deserialize(stream);

Console.WriteLine(root.A);
Console.WriteLine(root.B);

foreach (var pair in root.Dict)
    Console.WriteLine(pair);

这篇关于用未知字段反序列化XML-会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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