<root>
<channel>
<one>example</one>
<two>example2</two>
</channel>
<channel>
<one>example</one>
</channel>
</root>
In the second node, I don’t have a <two> node. If I use this: root.channel.two obviously I get the error “Method missing”. How can I check to avoid this error? What is the conditional statement I would use?
Technique 1: Rescue Any Error
Technique 2: Look Before Leaping (aka Don’t Use Slop)
The (no-slop) code
some_node.at_xpath("foo")is identical tosome_node.foowhen using slop, except that it returnsnilwhen no child node with that name exists. Indeed, the implementation of Slop just callsxpathfor the element name: if it finds many elements, you get that Nodeset; if it finds only one element, it gives you that; if it finds no elements, it raises theNoMethodError. The important bits look like this:Here’s what the Nokogiri documents say about Slop (in the footnotes):
In general, XPath is way more powerful and faster than slop traversal. For example, if you want to iterate over every
<two>node, you can do:If you describe what you really need to do in the end, we can help you craft better code. In my personal opinion Slop is generally a less-effective way to traverse a document.