技术 1:挽救任何错误
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
技巧 2:三思而后行(又名不要使用斜坡)
%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
(无溢出)代码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
以下是 Nokogiri 文件中关于 Slop 的描述(在脚注中):
不要使用这个。
不,真的,不要使用这个。如果您使用它,请不要报告错误。
已警告您!
一般来说,XPath 比 slop 遍历更强大、更快。例如,如果您想迭代每个<two>
节点,你可以这样做:
d.xpath('/root/channel/two').each do |two|
# This will only find nodes that exist
end
如果您描述最终真正需要做什么,我们可以帮助您编写更好的代码。在我个人看来,Slop 通常是一种效率较低的遍历文档的方式。