我已经提供了XML,我无法更改,我需要将其反序列化为自定义类:
<Person>
<Addresses>
<MainAddress>
<Country />
<City />
</MainAddress>
<AdditionalAddress>
<Country />
<City />
</AdditionalAddress>
<AdditionalAddress>
<Country />
<City />
</AdditionalAddress>
... other additional addresses
</Addresses>
... other elements
</Person>
然后我反序列化:
XmlSerializer serializer = new XmlSerializer(typeof(Person), namespace);
Person person = serializer.Deserialize(stream) as Person;
反序列化器可以在反序列化简单元素的情况下正常工作。 当有像地址这样的元素时,我在其类上实现了IXmlSerializable:link text
问题是reader.ReadElementContentAsString()不能与复杂元素一起使用。
答案 0 :(得分:4)
Adressess类应以这种方式声明:
[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; }
}
答案 1 :(得分:0)
此外,如果根对象类型具有命名空间,则必须对嵌套类型使用相同的命名空间。
示例:
[System.Xml.Serialization.XmlRootAttribute(Namespace = "some namespace")]
class Person {...}
[System.Xml.Serialization.XmlRootAttribute(Namespace = "some namespace")]
class MainAddress{...}