XML Serializer - 反序列化XML数组

时间:2015-03-20 13:55:59

标签: c# xmlserializer

我有以下示例XML:

<PossibleAddresses>
    <Address tempid="12345">1 The Street England</Address>
    <Address tempid="6789">2 The Street England</Address>
    <Address tempid="4321">3 The Street England</Address>
    <Address tempid="1111">4 The Street England</Address>
</PossibleAddresses>

我正在尝试对此XML进行反序列化,以便我基本上只返回一个“地址”列表。包含两个属性的对象。一个是“天真地”&#39;另一个是实际的地址字符串本身。

我的班级看起来像这样:

[XmlRoot("PossibleAddresses")]
    public class Addresses
    {
        [XmlArrayItem("Address", Type = typeof(Address))]
        public List<Address> PossibleAddresses { get; set; }
    }

    public class Address
    {
        [XmlAttribute(AttributeName = "tempid")]
        public string TempId { get; set; }

        [XmlElement(ElementName = "Address")]
        public string FullAddress { get; set; }
    }

然后我使用XmlSerializer来反序列化XML。 T是班级&#39;地址&#39;:

public static T DeserializeObject<T>(string data)
        {
            var ser = new XmlSerializer(typeof(T));
            return (T)ser.Deserialize(new StringReader(data));
        }

目前,这将成功反序列化。我最后得到一个空的地址列表。

2 个答案:

答案 0 :(得分:3)

FullAddress此处应使用属性XmlText

[XmlText]
public string FullAddress { get; set; }

答案 1 :(得分:1)

GoogleHireMe是正确的,您需要XmlText属性。

public class Address
{
    [XmlAttribute(AttributeName = "tempid")]
    public string TempId { get; set; }
    [XmlText]
    public string FullAddress { get; set; }
}

但是,您可以直接将地址反序列化为数组:

var serializer =
    new XmlSerializer(
        typeof(Address[]),
        new XmlRootAttribute("PossibleAddresses"));
Address[] items;

using(var stream = new StringReader(xml))
using(var reader = XmlReader.Create(stream))
{
    items = (Address[]) serializer.Deserialize(reader);
}