Xpath returns nothing to nokigiri

Possible duplicate:
Nokogiri / Xpath namespace query

Assume XML exists

<?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 do:

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

and shows nothing.

What am I doing wrong?

+4
source share
2 answers

Your xml is in the namespace "some_namespace", but your xpaths do not have a namespace binding. You essentially request different elements than in your XML. Using Clark's notation , the element you are trying to find is {some_namespace} ShortMessage, but you are requesting ShortMessage in the no namespace. Just because there is no prefix, i.e. The namespace is the default namespace, does not mean that you can ignore it.

+3
source

If you do not want to deal with namespaces, you can use

 doc.remove_namespaces! 

This is Lazy (= effective), but it is not recommended.

+8
source

Source: https://habr.com/ru/post/1444998/


All Articles