How to deserialize XML with multiple nested items?

后端 未结 2 1910
抹茶落季
抹茶落季 2021-01-05 14:50

I have given XML that I can\'t change and I need to deserialize it to a custom class:


   
       
                 


        
相关标签:
2条回答
  • 2021-01-05 15:55

    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; }
    }
    
    0 讨论(0)
  • 2021-01-05 15:57

    Also if the root object type has a namespace, you must use the same namespace for the nested types.

    Example:

    [System.Xml.Serialization.XmlRootAttribute(Namespace = "some namespace")]
    class Person {...}
    
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "some namespace")]
    class MainAddress{...}
    
    0 讨论(0)
提交回复
热议问题