反序列化xml返回空

时间:2013-01-04 16:05:15

标签: c# xml deserialization

这是反序列化的代码:

XmlRootAttribute xRoot = new System.Xml.Serialization.XmlRootAttribute();
xRoot.ElementName = "myList";
xRoot.IsNullable = true;
xRoot.Namespace = "http://schemas.datacontract.org/2006/05/Blah.Blah.Blah";
XmlSerializer serializer = new XmlSerializer(typeof(myList), xRoot);
XmlReader reader = new System.Xml.XmlTextReader(url);
myList myDeserializedList = (myList)serializer.Deserialize(reader);
reader.Close();

myDeserializedList为空,但是当我转到URL时,我看到一个非常大的XML。

以下是我的课程:

[Serializable()]
public class myItem
{
    [System.Xml.Serialization.XmlElement("Key")]
    public long Key { get; set; }
    [System.Xml.Serialization.XmlElement("Discount")]
    public double Discount { get; set; }
}


[Serializable, System.Xml.Serialization.XmlRoot("myList")]
public class myList
{
    [System.Xml.Serialization.XmlArray("myList")]
    [System.Xml.Serialization.XmlArrayItem("myItem", typeof(myItem))]
    public List<myItem> myItem { get; set; }
}

这是xml:

<myList xmlns="http://schemas.datacontract.org/2006/05/Blah.Blah.Blah" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <myItem>
        <Key>3465</Key>
        <Discount>0.00000000</Discount>
    </myItem>
</myList>

1 个答案:

答案 0 :(得分:4)

您的代码正在尝试读取/写入如下所示的XML:

<myList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.datacontract.org/2006/05/Blah.Blah.Blah">
  <myList>
    <myItem>
      <Key>3465</Key>
      <Discount>0.00000000</Discount>
    </myItem>
  </myList>
</myList>

注意包装集合的第二个myList标记。

您需要做的就是放弃XmlArrayXmlArrayItem属性,而是使用XmlElement。这将指示XmlSerializer将项目集合置于内联而不是嵌套在另一个元素中。

[Serializable, System.Xml.Serialization.XmlRoot("myList")]
public class myList
{
    [XmlElement]
    public List<myItem> myItem { get; set; }
}

编辑:此外,您不需要使用大多数属性; XmlSerializer很好地应用了默认值,重新声明它们变得有点多余,所以你可能只有:

public class myItem
{
    public long Key { get; set; }
    public double Discount { get; set; }
}

public class myList
{
    [XmlElement]
    public List<myItem> myItem { get; set; }
}

甚至抛弃了xRoot.ElementName = "myList";行,它仍会产生完全相同的XML。如果您想明确表达您的期望,或者您希望在不更改XML的情况下更改属性/类标识符,请随意保留它。