RE: [xml] XPath question

I know the thread is quite old, but for a long time I fell for the
common wisdom that you can't use XPath to query for an element in a
default namespace, and having recently discovered that it ain't so, I
want to set the record straight.

The following expression uses the XPath namespace-uri() and local-name()
functions to select all <n> elements whose namespace is "another-ns"
(the second <n> element in Igor's example):

  //*[namespace-uri()="another-ns" and local-name()="n"]

Igor's solution for selecting elements in a namespace (provide a
namespace prefix, apply it to each affected element, and use it in your
Xpath query) is commonly given.  I think this is a bad idea (unless you
have complete control over the documents you process, and arguably even
then), because there's no guarantee that the prefix in your query exists
in any given document, or if it does, that it refers to the same
namespace URI.  The namespace URI is authoritative, so it makes sense to
use it, as this expression does.

The only caveat is that I have no idea how efficiently an expression
like this is processed.

-----Original Message-----
From: xml-bounces gnome org [mailto:xml-bounces gnome org] On Behalf Of
Igor Zlatkovic
Sent: Monday, May 10, 2004 12:22 PM
To: Ed Day
Cc: xml gnome org
Subject: Re: [xml] XPath question

On 10.05.2004 18:09, Ed Day wrote:

I am relatively new to XPath, so perhaps there is something I don't 
understand here.  I am using the following XPath expression:


to try and match the following simple node:


This is coming back as a non-match. Apparently something in the 
namespace declaration is causing this.  If I remove that, or replace 
it with an attribute of a different name, the match is done OK.  The 
question is, if information on the namespace is required in the 
expression, what should it be?  Since it is the default namespace, it 
does not have a prefix.  So I don't know how to get this to match.

I am using the latest version of libxml2, but I am not sure this is a
libxml2 problem.  I got the same result when I used a different XPath
I am hoping some XPath guru out there can tell me what I am doing

Consider this document:

     <a xmlns="some-ns">
     <b xmlns="another-ns">

Now assume that those 'n' nodes inherit the default namespace from their
parents. How would you construct an XPath expression which selects any
one of the two 'n' nodes, but not the other?

To skip the boresome details, you cannot do what you are trying to. You
must give your namespace a prefix and include that prefix in your XPath


xml mailing list, project page xml gnome org

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]