Search code examples
xmlxpathxpath-2.0xpath-1.0

Need an optimized xpath expression to get the desired nodesets


I do have a sample XML file :-

<?xml version="1.0"?>    
<bookstore>
  <book>
     <title>The Weather Pattern</title>
     <author>Weather Man</author>
     <price>100.00</price>
  </book>
  <book>
     <title>Weaving Patterns</title>
     <author>Weaver</author>
     <price>150.00</price>
  </book>
  <book>
     <title>Speech Pattern</title>
     <author>Speaker</author>
     <price>15.00</price>
  </book>
  <book>
     <title>Writing Style</title>
     <author>Writer</author>
     <price>1500.00</price>
  </book>
</bookstore>

I write the XPATH expression as:

//author[starts-with(text(),'We')]/../*[local-name(.) = 'price' or local-name(.) = 'author']/text()

Output

Weather Man
100.00
Weaver
150.00

I am looking for a modified,simplified xpath expressions to get the same output. Different thought is also welcome.Any help?


Solution

  • This is a modified XPath expression. It gives the same output. Simplicity is in the eyes of the beholder.

    //book[starts-with(author, "We")]/*[not(local-name(.)="price")]/text()
    

    Or, without local-name, which makes sense only if different namespaces are involved:

    //book[starts-with(author, 'We')]/*[self::author or self::title]/text()
    //book[starts-with(author, 'We')]/*[not(self::price)]/text()