[英]Deserialization of key value pair in XML to c# object
我有如下所示的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 ?
}
需要建议。
您可以使用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.