Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select an XML-node based on its content?

Tags:

xml

xpath

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>
like image 233
Cros Avatar asked Aug 27 '08 13:08

Cros


People also ask

How do I select a specific node in XML?

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.

How selecting XML data is possible with XPath explain?

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.


2 Answers

/books/book/authors/author[contains(., 'Ritchie')]

or

//author[contains(., 'Ritchie')]
like image 109
aku Avatar answered Sep 23 '22 04:09

aku


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;
like image 41
Cros Avatar answered Sep 23 '22 04:09

Cros