如何使用linq获取xml代码的属性值

时间:2014-01-09 22:13:34

标签: c#-4.0 xml-parsing linq-to-xml

<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值返回Master值。 如何使用LINQ to XMl实现它。

1 个答案:

答案 0 :(得分:0)

你没有真正展示你的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>

您可以像这样简单地获取所有不同Master的{​​{1}}属性值:

ID

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属性值。