LibXML-Ruby and XPath with namespaces
So, have you ever wasted a half hour coding while also driving yourself absolutely insane? Was it when you were playing with libxml-ruby and xpath?
Minutes ago I was coding up a xml-rpc webservice when I realized that I was unable to get the nodes that I was looking for with xpath.
As usual I searched google looking for other people having the same issue and nothing helpful came up. I knew I had to write this post when I saw this.
So my response xml looked somthing like this:
response = <<-REMOTE_XML
<?xml ...?>
<rootNode xmlns="http://happythanksgiving.com/htgn">
<list>
<item>hey</item>
<item>there</item>
</list>
</rootNode>
REMOTE_XML
My ruby was something like this:
document = XML::Parser.string(response).parse
namespace = 'http://happythanksgiving.com/htgn'
turkeys = document.find('/tvlw:rootNode//item', namespace)
But turkeys.sizewas always 0.
I the found out that I needed to add the namespace prefix to each element in the xpath find…. duhh!
document = XML::Parser.string(response).parse
namespace = 'http://happythanksgiving.com/htgn'
hotels = document.find('/tvlw:rootNode//htgn:item', namespace)
Note the xpath ”/tvlw:rootNode//item” changed to ”/tvlw:rootNode//htgn:item” (added the namespace prefix)
Hope this helps some poor hacker or me next July when I forget and start searching google. ;)
Comments
-
There seems to be something wrong with your example. The namespace tvlw is not declared and the “solution” you found doesn’t work.

