Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath doesn't return anything in Nokogiri [duplicate]

Tags:

xml

ruby

nokogiri

Possible Duplicate:
Nokogiri/Xpath namespace query

Suppose there is XML

<?xml version="1.0" encoding="utf-8"?> 
<SomeResponse xmlns="some_namespace"> 
  <Timestamp>......</Timestamp> 
  <Ack>Failure</Ack> 
  <Errors> 
    <ShortMessage>ShortMessage111.</ShortMessage> 
    <LongMessage>LongMessage111.</LongMessage> 
    <ErrorCode>1</ErrorCode> 
    <SeverityCode>Warning</SeverityCode> 
  </Errors> 
  <Errors> 
    <ShortMessage>ShortMessage222.</ShortMessage> 
    <LongMessage>LongMessage222.</LongMessage> 
    <ErrorCode>2</ErrorCode> 
    <SeverityCode>Warning2</SeverityCode> 
  </Errors>
  <!-- there might be many Errors nodes -->
  <Version>123</Version> 
  <Build>122345abt_3423423</Build> 
</SomeResponse> 

I try to find all errors and their long and short messages using Nokogiri.

I'm doing:

doc = Nokogiri.XML(xml)
errors = doc.xpath("//Errors")
puts errors

errors2 = doc.xpath("//Errors//ShortMessage")
puts errors

and it shows nothing.

What am I doing wrong?

like image 332
Alan Coromano Avatar asked Nov 09 '12 06:11

Alan Coromano


2 Answers

If you don't want to deal with namespaces, you can use

doc.remove_namespaces!

It is Lazy (= efficient), but it is not recommended.

like image 61
nurettin Avatar answered Nov 10 '22 23:11

nurettin


Your XML is in the namespace some_namespace but your XPaths don't have a namespace binding. You're essentially querying different elements than are in your XML.

Using "Clark notation", the element you're trying to get to is

{some_namespace}ShortMessage

but you're querying for ShortMessage in the no-namespace.

Just because there is no prefix, i.e. the namespace is the default namespace, doesn't mean you can ignore it.

like image 6
nine9ths Avatar answered Nov 10 '22 23:11

nine9ths