C#将XML反序列化为实体

时间:2015-07-27 13:09:27

标签: c# xml collections deserialization

我试图将这个XML文档deseaqralize为Car对象列表,但它是空的。

以下是基于此帖子的示例XML文档:   How to Deserialize XML document

<?xml version="1.0" encoding="utf-8"?>
<Cars>
  <car id="1">
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </car>
  <car id="2">
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </car>
  <car id="3">
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </car>
</Cars>

必修课程:

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlAttribute("id")]
    public int id { get; set; }

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

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

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

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

反序列化函数:

public void ParseReturnXmlForVirtualEvent2()
{
    Cars cars = null;
    string path = @"E:\Projects\Newcars.xml";

    XmlDocument pdoc = new XmlDocument();
    pdoc.Load(path);
    XDocument Doc = new XDocument();
    Doc = XDocument.Parse(pdoc.OuterXml);            

    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Cars));

    System.Xml.XmlReader reader = Doc.CreateReader();
    cars = (Cars)serializer.Deserialize(reader);
    reader.Close();

    //return cars;
}

如果您需要我提供更多详细信息,请与我们联系。

2 个答案:

答案 0 :(得分:2)

您可以通过将Car属性替换为:

来解决此问题
[XmlElement("car", typeof(Car))]
public List<Car> Car { get; set; }

您的代码有三个问题:

  1. 你指定&#34; Car&#34;作为元素的名称但它实际上是&#34; car&#34;。
  2. Car属性不应该使用[XmlArray("Cars")]进行修饰,因为&#34; Cars&#34; XML元素已在Cars类本身上定义。
  3. Car属性应使用XmlElement而非XmlArrayItem定义。

答案 1 :(得分:1)

您需要在xml文件中大写car。元素应如下所示:

<Car id="1">
  <StockNumber>1020</StockNumber>
  <Make>Nissan</Make>
  <Model>Sentra</Model>
</Car>