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!
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.
<movie>
<title>The Shawshank Redemption</title>
<year>1994</year>
<director>Frank Darabont</director>
</movie>XML is widely used for data exchange between various applications and over the web.
XML files often have the extension .xml.
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:
gem install nokogiriNokogiri supports both XML and HTML parsing.
Let's parse the XML example we provided earlier using Nokogiri.
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').textThe // notation in the XPath query selects all elements that match the given tag name, regardless of their position in the XML document.
You can also parse local XML files by specifying the file path instead of opening a URI.
Nokogiri allows you to work with individual XML nodes, as well as with collections of nodes.
# 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')Remember to save the XML file to see your changes.
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.
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! 🤖🎉🚀