【问题标题】:How to get the attribute value of an xml code using linq如何使用linq获取xml代码的属性值
【发布时间】:2014-01-28 17:16:02
【问题描述】:
<Shape ID="1" NameU="Start/End" Name="Start/End" Type="Shape" Master="2">
....</Shape>
<Shape ID="2" NameU="Start/End" Name="Start/End" Type="Shape" Master="5">
....</Shape>
我必须为每个 ID 值返回主值。
我如何通过使用 LINQ to XMl 来实现它。
【问题讨论】:
标签:
c#-4.0
xml-parsing
linq-to-xml
【解决方案1】:
您并没有真正展示您的 XML 文档的外观,所以我假设它如下所示:
<Shapes>
<Shape ID="1" NameU="Start/End" Name="Start/End" Type="Shape" Master="2">
</Shape>
<Shape ID="2" NameU="Start/End" Name="Start/End" Type="Shape" Master="5">
</Shape>
</Shapes>
您可以像这样简单地获取所有不同ID 的Master 属性值:
var xDoc = XDocument.Load("Input.xml");
var masters = xDoc.Root
.Elements("Shape")
.ToDictionary(
x => (int)x.Attribute("ID"),
x => (int)x.Attribute("Master")
);
masters 将是Dictionary<int, int>,其中键是您的ID,值是对应的Master 属性值。