将XML转换为对象时面临的问题

时间:2018-11-12 15:33:51

标签: c# xml-serialization

我正在尝试将以下XML转换为对象,

<Addresses><Address><AddressLine1>61A PEEL ST</AddressLine1><AddressLine2></AddressLine2><Suburb>WEST MELBOURNE</Suburb><State>VIC</State><PostCode>3003</PostCode></Address><Address><AddressLine1>U 101/61 PEEL ST</AddressLine1><AddressLine2></AddressLine2><Suburb>WEST MELBOURNE</Suburb><State>VIC</State><PostCode>3003</PostCode></Address><Address><AddressLine1>U 102/61 PEEL ST</AddressLine1><AddressLine2></AddressLine2><Suburb>WEST MELBOURNE</Suburb><State>VIC</State><PostCode>3003</PostCode></Address><Address><AddressLine1>59 PEEL ST</AddressLine1><AddressLine2></AddressLine2><Suburb>WEST MELBOURNE</Suburb><State>VIC</State><PostCode>3003</PostCode></Address><Address><AddressLine1>63 PEEL ST</AddressLine1><AddressLine2></AddressLine2><Suburb>WEST MELBOURNE</Suburb><State>VIC</State><PostCode>3003</PostCode></Address><Address><AddressLine1>63A PEEL ST</AddressLine1><AddressLine2></AddressLine2><Suburb>WEST MELBOURNE</Suburb><State>VIC</State><PostCode>3003</PostCode></Address><Address><AddressLine1>57 PEEL ST</AddressLine1><AddressLine2></AddressLine2><Suburb>WEST MELBOURNE</Suburb><State>VIC</State><PostCode>3003</PostCode></Address><Address><AddressLine1>57A PEEL ST</AddressLine1><AddressLine2></AddressLine2><Suburb>WEST MELBOURNE</Suburb><State>VIC</State><PostCode>3003</PostCode></Address></Addresses>

使用下面的代码反序列化XML,

XmlSerializer serializer = new XmlSerializer(typeof(Addresses));
            using (TextReader reader = new StringReader(addressValidationResult.Alternates))
            {
                Addresses result = (Addresses)serializer.Deserialize(reader);
            }

使用“ addressValidationResult.Alternates”作为结果提供上述XML字符串。

PFB我的模型,

namespace Models
{
    public class Addresses
    {
         public List<Address> AddressesList { get; set; }
    }

    public class Address{
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string Suburb { get; set; }
        public string State { get; set; }
        public string PostCode { get; set; }
    }
}

结果是带有一个空列表的,没有任何数据。该代码不会引发异常,但是数据也不会得到转换。

请让我知道我在这里想念的东西

1 个答案:

答案 0 :(得分:0)

用于反序列化的模型和代码看起来正确,唯一缺少的是一些XmlElement属性。这里的关键解决方案是在[XmlElement("Address")]属性中添加AddressesList

    [XmlRoot("Addresses")]
    public class Addresses
    {
        [XmlElement("Address")]
        public List<Address> AddressesList { get; set; }
    }

    public class Address
    {
        [XmlElement("AddressLine1")]
        public string AddressLine1 { get; set; }
        [XmlElement("AddressLine2")]
        public string AddressLine2 { get; set; }
        [XmlElement("Suburb")]
        public string Suburb { get; set; }
        [XmlElement("State")]
        public string State { get; set; }
        [XmlElement("PostCode")]
        public string PostCode { get; set; }
    }