本文介绍了如何反序列化与多个嵌套项目XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我给XML,我无法改变,我需要将其反序列化到一个自定义类:
I have given XML that I can't change and I need to deserialize it to a custom class:
<Person>
<Addresses>
<MainAddress>
<Country />
<City />
</MainAddress>
<AdditionalAddress>
<Country />
<City />
</AdditionalAddress>
<AdditionalAddress>
<Country />
<City />
</AdditionalAddress>
... other additional addresses
</Addresses>
... other elements
</Person>
然后我反序列化:
Then I deserialize:
XmlSerializer serializer = new XmlSerializer(typeof(Person), namespace);
Person person = serializer.Deserialize(stream) as Person;
解串器工作正常的情况下,简单的元素反序列化。
当有喜欢的地址元素我于它的类实现IXmlSerializable的喜欢这里:链接文本
问题在于reader.ReadElementContentAsString()不能与复杂的元素一起使用。
The problem is that reader.ReadElementContentAsString() cannot be used with complex elements.
推荐答案
Adressess类应该这样声明:
Adressess class should be declared this way:
[XmlRoot("Adressess")]
public class Adressess
{
[XmlElement(ElementName = "MainAddress")]
public MainAddress Main { get; set; }
[XmlElement(ElementName = "AdditionalAddress")]
public List<AdditionalAddress> AdditionalAddresses { get; set; }
}
[XmlRoot("MainAddress")]
public class MainAddress
{
public string Country { get; set; }
public string City { get; set; }
}
[XmlRoot("AdditionalAddress")]
public class AdditionalAddress
{
public string Country { get; set; }
public string City { get; set; }
}
这篇关于如何反序列化与多个嵌套项目XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!