How do I search for a node using a Linq to XML query?
Below doc xml
<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">
<innersection 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 property property1, section name = "B" and subsection name = "B" and innersection name = "B" in one query using linq for xml.
+2
source to share
3 answers
Here's my alternative to Jon's, assuming Property1 occurs only once inside innersection and you only need 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");
+5
source to share
EDIT: Removed LINQ to XML "normal" query style since ssg is better. However, I wanted to keep the XPath version. It hasn't been tested, but I think it should work ...
var properties = doc.XPathSelectElements(
"//section[@name='B']/subsection[@name='B']/innersection[@name='B']/property1");
+4
source to share
Since this question has also been tagged as vb.net, here is the equivalent of the ssg request 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>
+1
source to share