Nokogiri Recursively Find Children/Child from a Parent

Contrary to the pages of complex hand-written recursive methods I found on StackOverflow when Googling this, it is actually as simple as

  noko = Nokogiri::XML("my_noko_file.xml")
  parent_node = noko.root.xpath("//MyNodeName")
  children_named_floyd = parent_node.xpath(".//Floyd")

If you want to search on more complex criteria, you can also add in extra sauce to your xpath.

  noko = Nokogiri::XML("my_noko_file.xml")
 # Searches your entire XML tree for an XML node type "MyNodeName" that has an attribute "id" set to a value of '1234'
 # Then grabs the XML node of type "Something" from within the found NodeSet
  parent_node = noko.root.xpath("//MyNodeName[@id='1234']").at("Something")
  # Grab all children of the "Something" node that are of type "Floyd"
  children_named_floyd = parent_node.xpath(".//Floyd")

Nokogiri is a great gem. But I do often wish it’s docs had more examples and less byzantine explanations for common operations like these. But in the meantime, let’s hope Google will continue to fill in the gaps.

One Reply to “Nokogiri Recursively Find Children/Child from a Parent”

  1. This was so helpful! I’ve been searching and searching for a way to do what you just said!

    Now i just have to find a way to differentiate between a node found inside a node and a parent node.

Leave a Reply

Your email address will not be published. Required fields are marked *