How can I use XPath to select an XML-node based on its content?
If I e.g. have the following xml and I want to select the <author>-node that contains Ritchie to get the author's full name:
<books>
<book isbn='0131103628'>
<title>The C Programming Language</title>
<authors>
<author>Ritchie, Dennis M.</author>
<author>Kernighan, Brian W.</author>
</authors>
</book>
<book isbn='1590593898'>
<title>Joel on Software</title>
<authors>
<author>Spolsky, Joel</author>
</authors>
</book>
</books>
To find nodes in an XML file you can use XPath expressions. Method XmlNode. SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.
XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages.
/books/book/authors/author[contains(., 'Ritchie')]
or
//author[contains(., 'Ritchie')]
The XPath for this is:
/books/book/authors/author[contains(., 'Ritchie')]
In C# the following code would return "Ritchie, Dennis M.":
xmlDoc.SelectSingleNode("/books/book/authors/author[contains(., 'Ritchie')]").InnerText;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With