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?
If you don't want to deal with namespaces, you can use
doc.remove_namespaces!
It is Lazy (= efficient), but it is not recommended.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With