2012-02-20 214 views
2
<World> 
    <Animals> 
    <Tab> 
     <Dogs id ="1"> 
     <Dog1></Dog1> 
     <Dog2></Dog2> 
     <Dog3></Dog3> 
     </Dogs> 
     <Dogs id ="2"></Dogs> 
     <Dogs id ="3"></Dogs> 
    </Tab> 
    </Animals> 
</World> 

如何获取标签下的所有元素,其中id == 1?C#Linq to XML查询

我的Linq查询。 (不起作用)为什么?

XDocument xml= XDocument.Load(xml.xml); 
var elements = from e in xml.Descendants("Animals").Descendants("Tab").Elements("Dogs") 
where e.Attribute("id").toString().Equals("1") 
select c; 

请问您能检查一下吗?

谢谢!

回答

3
var result = xdoc.Descendants("World") 
       .Descendants("Animals") 
       .Descendants("Tab") 
       .Elements("Dogs") 
       .Where(n => n.Attribute("id").Value == "1"); 

输出:

<Dogs id="1"> 
    <Dog1></Dog1> 
    <Dog2></Dog2> 
    <Dog3></Dog3> 
</Dogs> 
+0

谢谢!问题出在n.Attiribute(“id”)。VALUE。 (我忘了加.value) – 2012-02-20 15:27:46

+0

:)不客气! – sll 2012-02-20 15:29:05

1

从你的样本数据我想你想

//from e in xml.Descendants("Animals").Descendants("Tab").Elements("Dogs") 
from e in xml.Descendants("Animals").Elements("Tab").Descendants("Dogs") 

而且在同一直线上,Descendants("Animals")可能是Elements("Animals")如果要强制执行的结构。

其余的查询看起来没问题。

1

或者使用XPath:

xml.XPathSelectElements("/World/Animals/Tab/Dogs[@id=1]") 

xml.XPathSelectElements("//Dogs[@id=1]")

任何地方发生哪些会发现所有的狗。

+0

只有当你想要“动物”之外的狗也是如此。 – 2012-02-20 15:56:57