Re: [xml] XPath with default namespace



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:

  http://bugzilla.gnome.org/show_bug.cgi?id=57644

  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)
           xpathCtxt->nsNr++;
   }

  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", "http://www.w3.org/Graphics/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.

Daniel

-- 
Daniel Veillard      | Red Hat Network http://redhat.com/products/network/
veillard redhat com  | libxml Gnome XML XSLT toolkit  http://xmlsoft.org/
http://veillard.com/ | Rpmfind RPM search engine http://rpmfind.net/
Sep 17-18 2001 Brussels Red Hat TechWorld http://www.redhat-techworld.com




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