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 sawthis.

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('/htgn: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('/htgn:rootNode//htgn:item', namespace)

Note the xpath ”/htgn:rootNode//item” changed to ”/htgn:rootNode//htgn:item” (added the namespace prefix)

Hope this helps some poor hacker or me next July when I forget and start searching google. 😉

Advertisements

2 responses to “LibXML-Ruby and XPath with namespaces”

  1. Les Nightingill says :

    There seems to be something wrong with your example. The namespace tvlw is not declared and the “solution” you found doesn’t work.

  2. Paul says :

    Hi Les, thanks for the tip on the namespace. I had a typo in my example, the ‘tvlw’ should have been ‘htgn.’ This example doesn’t work because the namespace is fictitious. If you replace the namespace uri and name with the one you are working on you will find that it does work.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: