2014-01-21 84 views
0

我想從使用C#的API反序列化XML響應。我無法獲得ItemList元素的值。我能夠得到ItemList以外的其他元素。一個示例XML在下面,並且在下面是Classes,最後是序列化函數。反序列化XmlArray沒有填充

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(); 
+0

xmlarray在responseclass的ITEMLIST ....和像ITEMLIST類...並在項目屬性中刪除xmlarray ... – terrybozzio

+0

的作品,由於消除xmlroot一些修改! –

+0

不僅僅是我所說的全部...元素1它將使用您在xelement的ctor中提供的名稱創建... – terrybozzio

回答

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; } 
}