反序列化XmlArray没有填充

时间:2014-01-21 02:38:09

标签: c# deserialization

我正在尝试使用C#从API反序列化XML响应。我无法获得ItemList元素的值。我能够获得ItemList以外的其他元素。下面是一个示例XML,下面是Classes,最后是serialize函数。

XML:

<Root xmlns="http://whatever">
    <Child1>
        <ChildElement1>16f09999</ChildElement1>
    </Child1>
    <ItemList>
        <Element1>
        ...
        </Element1>

        <Item>
            <ItemElem1>12345567</ItemElem1>
            <ItemElem2>12356465784</ItemElem2>
           ...
            <ItemAttributes>
            ...
            </ItemAttributes>
        </Item>
        <Item>
        ...
        </Item>
    </ItemList>
</Root>

[Serializable()]
[System.Xml.Serialization.XmlRoot("Root")]
public class ResponseClass
{
    [System.Xml.Serialization.XmlElement("Child1")]
    public OperationRequest OperationRequest { get; set; }

    [System.Xml.Serialization.XmlElement("ItemList")]
    public ItemList ItemList { get; set; }
}

类别:

[Serializable()]
[System.Xml.Serialization.XmlRoot(ElementName = "ItemList")]
public class ItemList
{
    [XmlArray("ItemList")]
    [XmlArrayItem("Item", typeof(Item))]
    public Item item { get; set; }

    [System.Xml.Serialization.XmlElement("Element1")]
    public int Element1 { get; set; }

}

串行器:

XmlSerializer serializer = new XmlSerializer(typeof(ResponseClass));

StreamReader reader = new StreamReader(path);
response = (ResponseClass)serializer.Deserialize(reader);
reader.Close();

1 个答案:

答案 0 :(得分:0)

请尝试以下方法。由于ItemList/Item不是XmlArray,因此您需要将其定义为简单的XmlElement

[Serializable()]
[System.Xml.Serialization.XmlRoot(ElementName = "Root", Namespace = "http://whatever")]
public class ResponseClass
{
    [System.Xml.Serialization.XmlElement("Child1")]
    public OperationRequest OperationRequest { get; set; }

    [System.Xml.Serialization.XmlElement("ItemList")]
    public ItemList ItemList { get; set; }
}

[Serializable()]
[System.Xml.Serialization.XmlRoot(ElementName = "ItemList", Namespace = "http://whatever")]
public class ItemList
{
    [System.Xml.Serialization.XmlElement("Item")]
    public Item[] Items { get; set; }

    [System.Xml.Serialization.XmlElement("Element1")]
    public int Element1 { get; set; }
}