将XML中的键值对反序列化为c#对象

时间:2014-02-17 05:06:56

标签: c# .net xml deserialization

我有XML,如下所示。

 <Device-array>
   <Device>
    <id>8</id>
    <properties>
     <PropKeyValuePair>...</PropKeyValuePair>
     <PropKeyValuePair>...</PropKeyValuePair>
    </properties>
   </Device>
   <Device>...</Device>
   <Device>...</Device>
 </Device-array>

我打算将它反序列化为C#对象,以便它更快。我只需要id字段。但我明白该类需要有一个数组(属性)。但我如何代表关键价值对?

[Serializable()]
public class SLVGeoZone
{
    [XmlElement("id")]
    public string id { get; set; } 

    //Arraylist of key value pairs here ?

 }

需要建议。

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ to XML而不是反序列化,并获得您需要的内容:ID列表:

var xDoc = XDocument.Load("FilePath.xml");

var ids = xDoc.Root
              .Elements("Device")
              .Select(x => (int)x.Element("id"))
              .ToList();

如果你真的需要使用反序列化,你可以省略你不需要的属性,XmlSerializer将反序列化刚声明的内容,跳过你未在类中声明的元素。

<强>更新

要获得更多信息,请将名称添加到匿名类型列表中:

var ids = xDoc.Root
              .Elements("Device")
              .Select(x => new {
                  Id =  (int)x.Element("id"),
                  Name = (string)x.Element("name")
              })
              .ToList();
相关问题