Reputation: 2053
I've been searching SO (and the rest of the Internet) for the answer, but I can't seem to find a solution for selecting an XML node based on an attribute.
Example XML:
<foo>
<bar name="do">A</bar>
<bar name="rae">B</bar>
<bar name ="mi">C</bar>
</foo>
So if I want to get B
by the rae
value of the name
attribute, I've tried:
myValue = myXML.selectSingleNode("//foo/bar/").Attributes.getNamedItem("rae").Text
Thanks!
Upvotes: 2
Views: 18444
Reputation: 2701
Using your example...
myValue = myXML.SelectSingleNode("/foo/bar[@name='rae']").InnerXML
Note the use of the @ in the variable name. Your criteria (everything between the square brackets) goes on the level that you are searching through.
Upvotes: 1
Reputation: 2053
The solution that ended up working for me is:
myValue = myXML.selectSingleNode("var[@name='ID']").Text
Upvotes: 3
Reputation: 2087
If there are multiple nodes, then I don't think you'd be able to use SelectSingleNode
. Instead, you can use XPath and getElementsByTagName. In addition, (though it may not be necessary in your case) to ensure that you're only getting one node, you can use NextNode
. The final code using your sample XML would be...
myValue = myXML.getElementsByTagName("/foo[@name='rae']/bar").nextNode.nodeTypedValue
Upvotes: 1