C#Linq到XML查询
如何在tag == 1的标签下获取所有元素?
我的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;
你能检查一下吗?
谢谢!
var result = xdoc.Descendants("World") .Descendants("Animals") .Descendants("Tab") .Elements("Dogs") .Where(n => n.Attribute("id").Value == "1");
输出:
或者使用XPath:
xml.XPathSelectElements("/World/Animals/Tab/Dogs[@id=1]")
要么
xml.XPathSelectElements("//Dogs[@id=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")
。
其余的查询看起来没问题。