无法确定元素是否存在 [英] Having trouble determining if element exists

查看:72
本文介绍了无法确定元素是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个充满嵌套 item 节点的 xml 文档.在大多数情况下,每个 item 都有一个 name 元素.我想检查 item 是否有 name 元素,如果不存在则返回一个默认名称.

I have an xml document full of nested item nodes. In most cases, each item has a name element. I want to check if an item has a name element, and return a default name if one doesn't exist.

<item>
  <name>Item 1</name>
</item>
<item>
    <items>
        <item>
          <name>Child Item 1</name>
        </item>
        <item>
          <name>Child Item 2</name>
        </item>
    </items>
</item>

当我向 node.at('name') 询问没有 name 元素的节点时,它会从树更下方的子节点中选择下一个.在上面的例子中,如果我在第二个 item 上询问 at('name'),我会得到 "Child Item 1".>

When I ask node.at('name') for the node with no name element, it picks the next one from the children further down the tree. In the case above, if I ask at('name') on the second item, I get "Child Item 1".

推荐答案

问题是您使用的是 at(),它可以接受 CSS 选择器或 XPath 表达式,并试图猜猜你给的是哪个.在这种情况下,它认为 name 是一个 CSS 选择器,它是一个后代选择器,选择当前节点下方任意位置的 name 元素.

The problem is you're using at(), which can accept either a CSS selector or an XPath expression, and tries to guess which you gave it. In this case it thinks that name is a CSS selector, which is a descendant selector, selecting name elements anywhere below the current node.

相反,您希望使用 XPath 表达式仅查找 child 元素.您可以通过使其明确为 XPath 表达式来做到这一点:

Instead, you want to use an XPath expression to find only child <name> elements. You can do this either by making it clearly an XPath expression:

node.at('./name')

或者你可以通过使用 at_xpath 方法来做到这一点:

or you can do it by using the at_xpath method to be clear:

node.at_xpath('name')

这是一个简单的工作示例:

Here's a simple working example:

require 'nokogiri'
doc = Nokogiri.XML '<r>
  <item id="a">
    <name>Item 1</name>
  </item>
  <item id="b">
      <items>
          <item id="c">
            <name>Child Item 1</name>
          </item>
          <item id="d">
            <name>Child Item 2</name>
          </item>
      </items>
  </item>
</r>'

doc.css('item').each do |item|
  name = item.at_xpath('name')
  name = name ? name.text : "DEFAULT"
  puts "#{item['id']} -- #{name}"
end

#=> a -- Item 1
#=> b -- DEFAULT
#=> c -- Child Item 1
#=> d -- Child Item 2

这篇关于无法确定元素是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆