Ruby Nokogiri: A Deep Dive into Parsing XML with Ruby

beginner
15 min

Ruby Nokogiri: A Deep Dive into Parsing XML with Ruby

Welcome to our comprehensive guide on using Ruby Nokogiri for parsing XML! This tutorial is designed for both beginners and intermediates, and we'll cover everything from the basics to advanced examples. Let's dive in!

🎯 Understanding XML

XML (eXtensible Markup Language) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.

xml
<movie> <title>The Shawshank Redemption</title> <year>1994</year> <director>Frank Darabont</director> </movie>

💡 Pro Tip:

XML is widely used for data exchange between various applications and over the web.

📝 Note:

XML files often have the extension .xml.

🎯 Installing Nokogiri

To install Nokogiri, you'll first need to ensure you have the latest version of Ruby. Once you have Ruby, you can install Nokogiri with the following command:

bash
gem install nokogiri

💡 Pro Tip:

Nokogiri supports both XML and HTML parsing.

🎯 Parsing XML with Nokogiri

Let's parse the XML example we provided earlier using Nokogiri.

ruby
require 'nokogiri' require 'open-uri' # Load the XML file xml_string = open('movie.xml').read # Parse the XML string doc = Nokogiri::XML(xml_string) # Access the title, year, and director elements puts doc.xpath('//title').text puts doc.xpath('//year').text puts doc.xpath('//director').text

📝 Note:

The // notation in the XPath query selects all elements that match the given tag name, regardless of their position in the XML document.

💡 Pro Tip:

You can also parse local XML files by specifying the file path instead of opening a URI.

🎯 Working with XML Nodes

Nokogiri allows you to work with individual XML nodes, as well as with collections of nodes.

ruby
# Access the first movie node movie_node = doc.xpath('//movie').first # Access the first child of the movie node (the title) title_node = movie_node.xpath('title').first # Change the title and save the changes to a new XML file title_node.content = 'The Green Mile' doc.save('movie_updated.xml')

📝 Note:

Remember to save the XML file to see your changes.

💡 Pro Tip:

You can use the at_xpath method to access a single node by its XPath, or the css method to use CSS selectors for more complex queries.

Quick Quiz
Question 1 of 1

What does Nokogiri help us to do in Ruby?

Continue exploring Ruby Nokogiri in our next lesson! Stay tuned for more advanced examples and practical applications. Happy coding! 🤖🎉🚀