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)
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. 😉