Nokogiri

Created at
7 June 2025
Last modified
7 June 2025
Status
🌱 seed
Tagged

Nokogiri is an XML and HTML parser for ruby. It's (as far as I'm aware) the de facto XML parser for ruby.

Cheat sheet

To load a file:

doc = File.open("file.xml"){ |f| Nokogiri::XML(f) }

You can select elements using either CSS selectors, or using XPath. If you're using CSS, you may want to specify a heirarchy to ensure you have the correct path. Nokogiri correctly identifies the :root element.

To select all elements matching a given pattern:

# Selects all task elements which are the direct child of the root element
doc.search(":root > task")

To select only the first element matching a given pattern:

# Selects the first task element which is the direct child of the root element
doc.at(":root > task")

This also works on elements themselves:

fifth_task = doc.select(":root > task")[4]

task_project = fifth_task.at("project")