XPath expression to select all nodes
I would li开发者_运维问答ke to find all <Field />
nodes (that may be arbitrarily nested) inside a given XmlNode.
If do something like this:
foreach(XmlNode n in node.SelectNodes('//Field'))...
This returns all nodes in the entire document, not all nodes under node
.
Is this how XPath is supposed to work? I looked at some documents and it seems like the //Node
query should be scoped to whatever node it's invoked at.
Is there any other technique to select all nodes with a given name that are under a specific node?
If you use '//Field'
it's absolut from the root of the document. To search relative to the current node, just use './/Field'
.
Use ./Field
.
.//
Means descendants, which includes children of children (and so forth)../
Means direct children.
If a XPath starts with a /
it becomes relative to the root of the document; to make it relative to your own node start it with ./
.
try to use SelecteSingleNode()
Remove //
because otherwise it search among all the document irrelatively to the root node.
node.SelectNodes("Field")
You can use simple linq query like this:
var techLeads = (from value in element.Descendants ("Manager")
where value.Attribute ("Name").Value == "Mgr1"
select value).Descendants("TechLead");
Sample Xml:
<Employees> <Manager Name="Mgr1"> <TechLead Name="TL1" /> <TechLead Name="TL2" /> </Manager> </Employees>
精彩评论