Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath expression from xml with namespace prefix

I could not get the following xpath expression to work when the xml path namespace prefix set.

/bk:BookStore/bk:Books/bk:Book[text()='Time Machine']

XML is:

<BookStore xmlns:bk="http://www.bookstore.com/book#">
  <bk:Books>
    <bk:Book id="1">Time Machine></bk:Book>
  </bk:Books>
</bk:BookStore>
like image 934
Chaitanya Avatar asked Oct 14 '10 09:10

Chaitanya


2 Answers

Or even better (and more portable), without the unnecessary prefix:

/*/*[local-name()='Books'] ... and so on

The function local-name ignores any prefix, which, as correctly stated by commenters, can vary.

like image 172
Ivivi Vavava Avatar answered Oct 23 '22 21:10

Ivivi Vavava


Without more information about the host language (in which you attempt to evaluate XPath expressions) it is not possible to provide an useful recommendation.

Generally, one needs to "register" a namespace with a namespace manager and this also associates a prefix to the registered namespace. Then, using this NamespaceManager object as an argument to the XPath-evaluation method, one can specify as argument to this method an XPath expression that contains names prefixed by that particular prefix.

Workarounds:

/*/*[name()='bk:Books']/*[name()='bk:Book' and text()='Time Machine']
like image 28
Dimitre Novatchev Avatar answered Oct 23 '22 20:10

Dimitre Novatchev