Xpath不会在Nokogiri中返回任何内容[重复]

时间:2022-09-06 08:11:53

Possible Duplicate:
Nokogiri/Xpath namespace query

可能重复:Nokogiri / Xpath命名空间查询

Suppose there is XML

假设有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.

我尝试使用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?

我究竟做错了什么?

2 个解决方案

#1


3  

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.

您的xml位于名称空间“some_namespace”中,但您的xpath没有名称空间绑定。您实际上是在查询与XML中不同的元素。使用Clark表示法,您尝试访问的元素是{some_namespace} ShortMessage,但您在no名称空间中查询ShortMessage。仅仅因为没有前缀,即命名空间是默认命名空间,并不意味着你可以忽略它。

#2


8  

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

如果您不想处理命名空间,则可以使用

doc.remove_namespaces!

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

它是懒惰的(=有效的),但不推荐。

#1


3  

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.

您的xml位于名称空间“some_namespace”中,但您的xpath没有名称空间绑定。您实际上是在查询与XML中不同的元素。使用Clark表示法,您尝试访问的元素是{some_namespace} ShortMessage,但您在no名称空间中查询ShortMessage。仅仅因为没有前缀,即命名空间是默认命名空间,并不意味着你可以忽略它。

#2


8  

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

如果您不想处理命名空间,则可以使用

doc.remove_namespaces!

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

它是懒惰的(=有效的),但不推荐。