Getting Started with Nokogiri and XML in Ruby

Submitted on Jun 13, 2012, 8:50 a.m.

Here's a short post on getting started with Nokogiri - a Ruby gem that wraps libxml. I'm writing this because well, the docs at kind of suck. I wanted to read a simple XML document. My XPath fu was a little rusty, although all I wanted to do was read some attributes from a root element, some element values off of the root, and then a short collection of items (very similar to an Atom document). My main bone of contention with the docs was their use of the `@doc.xpath("//character")` search operator at the very beginning of their parsing tutorial. How about we start from the beginning:

Here is a sample XML document. Save this to your local disk, install the Nokogiri gem, and fire up IRB.

1<Collection version="2.0" id="74j5hc4je3b9">
2 <Name>A Funfair in Bangkok</Name>
3 <PermaLink>Funfair in Bangkok</PermaLink>
4 <PermaLinkIsName>True</PermaLinkIsName>
5 <Description>A small funfair near On Nut in Bangkok.</Description>
6 <Date>2009-08-03T00:00:00</Date>
7 <IsHidden>False</IsHidden>
8 <Items>
9 <Item filename="AGC_1998.jpg">
10 <Title>Funfair in Bangkok</Title>
11 <Caption>A small funfair near On Nut in Bangkok.</Caption>
12 <Authors>Anthony Bouch</Authors>
13 <Copyright>Copyright © Anthony Bouch</Copyright>
14 <CreatedDate>2009-08-07T19:22:08</CreatedDate>
15 <Keywords>
16 <Keyword>Funfair</Keyword>
17 <Keyword>Bangkok</Keyword>
18 <Keyword>Thailand</Keyword>
19 </Keywords>
20 <ThumbnailSize width="133" height="200" />
21 <PreviewSize width="532" height="800" />
22 <OriginalSize width="2279" height="3425" />
23 </Item>
24 <Item filename="AGC_1164.jpg" iscover="True">
25 <Title>Bumper Cars at a Funfair in Bangkok</Title>
26 <Caption>Bumper cars at a small funfair near On Nut in Bangkok.</Caption>
27 <Authors>Anthony Bouch</Authors>
28 <Copyright>Copyright © Anthony Bouch</Copyright>
29 <CreatedDate>2009-08-03T22:08:24</CreatedDate>
30 <Keywords>
31 <Keyword>Bumper Cars</Keyword>
32 <Keyword>Funfair</Keyword>
33 <Keyword>Bangkok</Keyword>
34 <Keyword>Thailand</Keyword>
35 </Keywords>
36 <ThumbnailSize width="200" height="133" />
37 <PreviewSize width="800" height="532" />
38 <OriginalSize width="3725" height="2479" />
39 </Item>
40 </Items>

From our IRB prompt - the first thing we'll do is require nokogiri.

1>> require 'nokogiri'
2=> true

Now let's load our XML document.

1>> f ="/path/to/the/collection.xml")
2=> #
3>> doc = Nokogiri::XML(f)
4=> # You'll see the XML document output to the console.

The first thing we'd like to do is select the id attribute from the root. There's two ways you can do this.

1>> doc.at_xpath("/*/@id")
2=> #

Which will return the XML Attribute (which inherits from Node). You can use `.value`, `.text`, or `.inner_text` against the returned object to retrieve the actual value. Notice we've used the `at_xpath` method to select the element. `xpath` on its own will return a node array (with just one element in this case). The second method to get a root attribute, is to select the root element first using.

1>> root = doc.root
2>> # again here you'll see the complete XML document output to the console.

Now we can access the id attribute using a convenient array notation - returning the value immediately, or the XPath statement for an attribute which again will return an XML::Attr object from which we can retrieve the value.

1>> root["id"]
2=> "74j5hc4je3b9"


1>> root.at_xpath("@id")
2=> #

Since we're already positioned at the root element of the document, selecting elements beneath the root is easy.

1>> root.at_xpath("Name")
2=> #]>

You can use `root.at_xpath("Name").text` to retrieve the text value, but only if you're absolutely sure the element is present, otherwise you'll get an undefined method for nil:NilClass exception. Now lets select the items in our document, returning a node array of items that we can iterate over.

1>> items = root.xpath("Items/Item")
2=> #You'll see the xml for our two items output to the console.
3>> items.count
4=> 2

We can select an attribute for an item using the convenient index style syntax, or a regular XPath select with the `@` sign.

1>> items[0]["filename"]
2=> "AGC_1998.jpg"

And of course we can repeat and rinse with all of our element selectors, as well as move further down the structure of the document and select the keywords.

1>> items[0].at_xpath("Title")
2=> #]>

And very lastly - although this is a very different use case, and for some reason the first one that the Nokogiri [parsing tutorial]( decided to present, is the `//` XPath search operator which will search and return all elements at all levels for a matching element name.

1>> doc.xpath("//Keywords")
2=> #returning an array of Keyword elements across the entire document, including at the root, and item levels.

Last but not least - we'll close our file.

1>> f.close

Of course the better way to do this in code is to use the ` do |f| end;` block to ensure that the file is closed at the end of our Nokogiri session. And there you have it. Hope this helps anyone else who is using Nokogiri for the first time and would like to get started with very basic XPath queries to select attributes and elements from a simple XML document.