Ruby tutorials - nokogiri

nokogiri

The XML file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

Read from file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
require 'nokogiri'
doc = Nokogiri::XML(File.open('books.xml'))
books = doc.xpath('/bookstore/book')
books.each do |book|
puts '------------------'
puts 'Category: ' + book.attr('category')
puts 'Title: ' + book.xpath('title')[0].content
puts 'Author: ' + book.xpath('author')[0].content
puts 'Year: ' + book.xpath('year')[0].content
puts 'Price: ' + book.xpath('price')[0].content
end
# return a single element
cooking_book = doc.at_xpath("/bookstore/book[@category='cooking']")
# Update content of an element
cooking_book_author = cooking_book.xpath('author')[0]
cooking_book_author.content = 'David Robinson'

Read from string

1
2
3
4
5
require 'nokogiri'
doc = Nokogiri::XML("<staff_list><staff><name>Paul</name></staff><staff><name>Andrew</name></staff></staff_list>")
puts doc.root
Share