Below the xml doc
<Root>
<Global>
</Global>
<local>
<section name="A">
<subsection name="A">
<innersection name="A">
<Property1>
</Property1>
</innersection>
<innersection name="B">
<Property1>
</Property1>
</innersection>
</subsection>
<subsection name="B">
<in开发者_开发技巧nersection name="A">
<Property1>
</Property1>
</innersection>
<innersection name="B">
<Property1>
</Property1>
</innersection>
</subsection>
</section>
<section name="B">
<subsection name="A">
<innersection name="A">
<Property1>
</Property1>
</innersection>
<innersection name="B">
<Property1>
</Property1>
</innersection>
</subsection>
<subsection name="B">
<innersection name="A">
<Property1>
</Property1>
</innersection>
<innersection name="B">
<Property1>
</Property1>
</innersection>
</subsection>
</section>
</local>
</Root>
Now i want the property1 whose section name="B" and subsection name="B" and innersection name="B" in one single query using linq to xml.
Here is my take, alternative to Jon's, assuming Property1 occurs only once inside an innersection and you need only that one:
var Property1 = doc.Root.Elements("local").Elements("section")
.Where(x => x.Attribute("name") == "B").Elements("subsection")
.Where(x => x.Attribute("name") == "B").Elements("innersection")
.Where(x => x.Attribute("name") == "B").Element("Property1");
EDIT: Removed LINQ to XML "normal" style of query as ssg's is better. I wanted to leave the XPath version though. It's untested, but I think it should work...
var properties = doc.XPathSelectElements(
"//section[@name='B']/subsection[@name='B']/innersection[@name='B']/property1");
Since this question was also tagged vb.net, here is the equivalent of ssg's query in vb.net:
Dim Property1 = doc.<local>.<section>.Where(Function(x) x.@name = "B") _
.<subsection>.Where(Function(x) x.@name = "B") _
.<innersection>.Where(Function(x) x.@name = "B") _
.<Property1>
精彩评论