tags:

views:

612

answers:

3

How can I use XPath to select an XML-node based on it's 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>
A: 

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;
Cros
+1  A: 

//author[contains(text(), 'Ritchie')]

Chris Marasti-Georg
+4  A: 
/books/book/authors/author[contains(., 'Ritchie')]

or

//author[contains(., 'Ritchie')]
aku