<root>
<channel>
<one>example</one>
<two>example2</two>
</channel>
<channel>
<one>example</one>
</channel>
</root>
Run Code Online (Sandbox Code Playgroud)
在第二个节点中,我没有<two>节点.如果我使用它:root.channel.two显然我得到错误"方法缺失".如何检查以避免此错误?我会用什么条件语句?
require 'nokogiri'
d = Nokogiri.XML("<foo><bar /></foo>")
bad = d.root.bar #=> undefined method `bar' for #<...> (NoMethodError)
d.slop!
yay = d.root.bar #=> #<... name="bar">
bad = d.root.xxx #=> undefined method `xxx' for #<...> (NoMethodError)
yay = d.root.xxx rescue nil #=> nil
Run Code Online (Sandbox Code Playgroud)
%w[ bar xxx ].each do |node_name|
if n = d.root.at_xpath(node_name)
puts "Yay! #{n}"
else
puts "No node named #{node_name}"
end
end
#=> Yay! <bar/>
#=> No node named xxx
Run Code Online (Sandbox Code Playgroud)
(no-slop)代码some_node.at_xpath("foo")与some_node.foo使用slop时的代码相同,只是nil在没有具有该名称的子节点时返回.实际上,Slop的实现只需要调用xpath元素名称:如果找到很多元素,你就得到了Nodeset; 如果它只找到一个元素,它会给你那个; 如果它没有找到任何元素,它会提升NoMethodError.重要的位看起来像这样:
def method_missing( name )
list = xpath(name)
if list.empty?
super # NoMethodError unless someone else handles this
elsif list.length == 1
list.first # Since we only found one element, return that
else
list # ...otherwise return the whole list
end
end
Run Code Online (Sandbox Code Playgroud)
以下是Nokogiri文件中关于Slop的内容(在脚注中):
不要使用它.
不,真的,不要使用它.如果您使用它,请不要报告错误.
你被警告了!
通常,XPath比slop遍历更强大,更快.例如,如果要迭代每个<two>节点,可以执行以下操作:
d.xpath('/root/channel/two').each do |two|
# This will only find nodes that exist
end
Run Code Online (Sandbox Code Playgroud)
如果您最终描述了您真正需要做的事情,我们可以帮助您制作更好的代码.在我个人看来,Slop通常是一种不太有效的遍历文档的方式.
| 归档时间: |
|
| 查看次数: |
7542 次 |
| 最近记录: |