本文介绍了XML 序列化 - 将部分 XML 保留为 XmlElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的对象:

I have an object something like this:

public class MyClass {
  public string AValue {get;set;}
  public XmlElement AdditionalConfig {get;set;}
}

我从一个如下所示的 XML 块中生成:

I'm generating this from a block of XML that looks like:

<MyClass>
  <AValue>Something</AValue>
  <AdditionalConfig>
    <NewNode Att="Value" />
  </AdditionalConfig>
</MyClass>

如果我使用 XmlSerializer 反序列化 XML,则 AdditionalConfig XmlElement 属性为 NewNode.现在,如果我在那里添加第二个元素:

If I use the XmlSerializer to de-serialize the XML then the AdditionalConfig XmlElement property is NewNode. Now, if I add a second element in there:

<MyClass>
  <AValue>Something</AValue>
  <AdditionalConfig>
    <NewNode Att="Value" />
    <AnotherNewNode />
  </AdditionalConfig>
</MyClass>

反序列化不起作用 - 它抱怨无法识别的元素AnotherNewNode".

The deserialization doesn't work - it complains about an unrecognised element 'AnotherNewNode'.

我尝试将 MyClass.AdditionalConfig 设为数组,但没有成功.如何将节点的所有内容放入 XmlElement 对象中?

I tried making MyClass.AdditionalConfig an array but no luck there. How would I get all the contents of the node into XmlElement objects?

一如既往,非常感谢

推荐答案

我不知道为什么这不起作用.但是,为了获得您需要的功能,您可以改为为您的附加元素引入一个 AdditionalConfig 容器类,如下所示:

I'm not sure why that doesn't work. However, to get the functionality you require, you can instead introduce an AdditionalConfig container class for your additional elements as follows:

public class AdditionalConfig
{
    [XmlAnyAttribute]
    public XmlAttribute[] attributes;
    [XmlAnyElement]
    public XmlElement[] elements;
}

public class MyClass
{
    public string AValue { get; set; }
    public AdditionalConfig AdditionalConfig { get; set; }
}

[XmlAnyElement] 当应用于 XmlElementXElement 类型的数组时,它会捕获要反序列化的 XML 中的任何和所有未知元素.同样[XmlAnyAttribute],如果需要,将 元素的未知属性捕获到 XmlAttribute 数组中.

[XmlAnyElement] when applied to an array of XmlElement or XElement types captures any and all unknown elements in the XML to be deserialized. Similarly [XmlAnyAttribute], if needed, captures unknown attributes of the <AdditionalConfig> element into an XmlAttribute array.

原型 fiddle.

这篇关于XML 序列化 - 将部分 XML 保留为 XmlElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 03:53