问题描述
在第一种情况下,一切都非常简单,我有以下XML,我可以反序列化到一个强类型。
In the first scenario, everything is pretty easy, I have the following XML, that I can deserialize to a strong type.
<providers>
<dprovider>
<dimensions>
<width></width>
</dimensions>
</dbrovider>
在第二个方案中,并这就是我需要帮助...我有东西多一点活力。
In the 2nd scenario, and this is where I need help... I have something a little more dynamic
<providers>
<dprovider>
<dimensions>
<width></width>
</dimensions>
</dbrovider>
<dprovider>
<dimensions>
<height></height>
</dimensions>
</dbrovider>
正如你所看到的尺寸子结构是两个项目不同,所以我需要找到一个方法来创建强类型的类,因此它可以处理任何改变尺寸的元素,它可以包含例如一个整体嵌套子结构,每个dbprovider不同。
As you can see the dimensions sub structure is different in both items, so I need to find a way to create the strongly typed class, so that it can handle any change to the dimensions element, it could for example contain a whole nested sub structure, different for each dbprovider.
这是如何做到这一点?
推荐答案
试试这个任何想法
[Serializable]
class Dimension { ... }
[Serializable]
class Height : Dimension { ... }
[Serializable]
class Width : Dimension { ... }
然后,在你的(注意是复数)元素反序列化到类,有此属性:
Then, in the class that your (note the plural) element deserializes into, have this property:
[XmlElement( Type = typeof( Height ), ElementName = "height" )]
[XmlElement( Type = typeof( Width ), ElementName = "width" )]
public Dimension[] DimensionArray {
get { ... }
set { ... }
}
下面的的文档(XmlElement的类),所以你可以计算出的其余的细节。
Here's the starting point of documentation on XML serialization (XmlElement class), so you can figure out the rest of the details.
您应该能够序列化/通过简单地从的System.Xml.Serialization 的命名空间。
You should be able to serialize/deserialize your providers object by simply decorating the right properties and classes with the right attributes from the System.Xml.Serialization namespace.
这篇关于反序列化动态XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!