Re: [xml] XPath with default namespace

Daniel Veillard wrote:

On Wed, Jul 18, 2001 at 10:07:57PM -0500, Charlie Bozeman wrote:
I've toyed around using XPath to locate elements but have not had much
luck (ver 2.4.0 and CVS). My xml file uses a default namespace; when I
remove it XPath works. To test it do:
testXPath -i test/SVG/a-wf.xml "//desc"

I get
Object is a Node Set :
Set contains 0 nodes:

I had a copy of version 2.3.9 lying around so I tried it and it worked.

  Hum, namespaces are tricky to handle properly in general...

  Well 2.3.9 was broken :-) Someone reported this already suggesting
it was a bug, it's not. I provided more complete explanation:

  basically '//desc' selects only element without namespace, that's the
semantic of the XPath spec.

  In general the solution is to pass the namespaces in scope to the XPath
evaluation, for example if you are on element node within document doc:

   xpathCtxt->namespaces = xmlGetNsList(doc, node);
   xpathCtxt->nsNr = 0;
   if (xpathCtxt->namespaces != NULL) {
       while (xpathCtxt->namespaces[xpathCtxt->nsNr] != NULL)

  This works okay but for the default namespace (it will be added to the
list but cannot be used for the description. Then the simplest is to
declare a namespace declaration like 'svg:' associated to this namespace

   xmlXPathRegisterNs(xpathCtxt, "svg", "";);

and query for //svg:desc (check the real URI for SVG Namespace, I invented it).
The good point is that this will work whether the given namespace is
the default one, or mapped to any other prefix. The XPath engine will do
the matching on the URI resolved using the prefix declared in the XPath
context and will ignore the actual prefix used in the instance.


Thanks for the info, I got it working with the default namespace. One
more thing, neither xmlXPathEval nor xmlXPathCompiledEval return NULL
when they don't find the desired expression. Am I correct to assume this
is because even an empty node set is a valid object? Do I need to check
the node set value's nodeNr to determine if it is empty or is there a
better mechanism.

Daniel Veillard      | Red Hat Network
veillard redhat com  | libxml Gnome XML XSLT toolkit | Rpmfind RPM search engine
Sep 17-18 2001 Brussels Red Hat TechWorld

xml mailing list
xml gnome org

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