libxml2 + XPath + local-name()
September 5, 2009 11:28 PM   Subscribe

Why does my XPath query need a local-name() call?

Here is an XML document I'm trying to yank stuff out of:

<?xml version="1.0" encoding="UTF-8"?>
<listallmycontainersresult xmlns="http://blah.blah.blah/">
<containers>
<container>
<name>abcd-1234</name>
<creationdate>2008-11-08T22:41:12.000Z</creationdate>
</container>
...
</containers>
</listallmycontainersresult>


I would have thought that the XPath query:

//container

would be enough to get an array of container nodes, but I actually need to send:

//*[local-name()='container']

Why is this more complex query required? Is there something I would need to do in order to be able to send a simpler query? I am using libxml2 to parse the XML document.
posted by Blazecock Pileon to Computers & Internet (3 answers total)
 
Best answer: Un-namespace-qualified names in an XPath expression always refer to the empty namespace, ignoring any xmlns="..." attribute in your document. You need an explicit prefix on all the namespaced elements in your XPath expression to workaround this.

For instance, add xmlns:blah="http://blah.blah.blah/" to your doc and then change your XPath to //blah:container.
posted by Khalad at 11:32 PM on September 5, 2009


Response by poster: You need an explicit prefix on all the namespaced elements in your XPath expression to workaround this.

Thanks for your explanation. I'm a bit new to libxml2. Is there a quick way to edit the xmlns attribute of listallmycontainersresult to create this alias?
posted by Blazecock Pileon at 11:40 PM on September 5, 2009


Response by poster: It looks like I can use xmlXPathRegisterNs(xpathCtx, prefix, href) to add an alias to a namespace when I perform the query.
posted by Blazecock Pileon at 12:08 AM on September 6, 2009


« Older WANT TO PRODUCE A FRAGRANCE: HOW?   |   Custom vs Yuppy furniture Newer »
This thread is closed to new comments.