简体   繁体   English

XmlSerializer.Deserialize List <>项目

[英]XmlSerializer.Deserialize on a List<> item

I've tried all the solutions I could find on SO and elsewhere, but can't seem to figure out why this is not working. 我已经尝试了所有可以在SO和其他地方找到的解决方案,但似乎无法弄清楚为什么这不起作用。

Straightforward deserialization of an XML string into an object, the object has one property - a List: 将XML字符串直接反序列化为对象,该对象具有一个属性 - 一个List:

[XmlTypeAttribute(AnonymousType = true)]
public class UpdateData
{
    [XmlArrayItem(ElementName = "Updates")]
    public List<Update> Updates { get; set; }

    public UpdateData()
    {
        Updates = new List<Update>();
    }

}

public class Update
{
    [XmlElement(ElementName = "MemberID")]
    public int MemberID { get; set; }

    [XmlElement(ElementName = "AnalysisID")]
    public int AnalysisID { get; set; }

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

    [XmlElement(ElementName = "RecordDate")]
    public DateTime RecordDate { get; set; }
}

Here is the deserialize code: 这是反序列化代码:

private object DeserialzeXml(string xml)
{
    var xmlSer = new XmlSerializer(typeof(UpdateData), new XmlRootAttribute("UpdateData"));
    var stringReader = new StringReader(xml);
    return xmlSer.Deserialize(stringReader);
}

And here is the XML: 这是XML:

<?xml version="1.0" encoding="utf-8" ?> 
<UpdateData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Updates>
        <Update>
            <MemberID>1</MemberID> 
            <AnalysisID>1</AnalysisID> 
            <MemberName>XXXXXXXXXXXXX</MemberName> 
        </Update>
        <Update>
            <MemberID>1</MemberID> 
            <AnalysisID>2</AnalysisID> 
            <MemberName>YYYYYYYYYYYYY</MemberName> 
        </Update>
        <Update>
            <MemberID>1</MemberID> 
            <AnalysisID>3</AnalysisID> 
            <MemberName>ZZZZZZZZZZZZ</MemberName> 
        </Update>
    </Updates>
</UpdateData>

This code compiles and runs, and returns an object of type UpdateData, but the Updates property is empty. 此代码编译并运行,并返回UpdateData类型的对象,但Updates属性为空。 Any ideas? 有任何想法吗?

Try changing the attributes on your list to this: 尝试将列表中的属性更改为:

[XmlArray(ElementName="Updates")]
[XmlArrayItem(ElementName="Update")]
public List<Update> Updates { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM