Java Reference
In-Depth Information
Parsing the document can throw all sorts of exceptions, as shown. Assuming nothing goes
wrong, after parsing, the code retrieves all the title elements. After getting the proper
element out of the NodeList and casting it to type Element , you then have to remem-
ber that the character data in the element is in the first text child of the element rather than
the element itself.
Here's the Groovy solution:
root = new XmlSlurper().parse('books.xml')
assert root.book[1].title == 'Making Java Groovy'
Wow. Groovy includes the XmlSlurper class, which is in the groovy.util package
(no import required). XmlSlurper has a parse method that builds the DOM tree and
returns the root element. Then it's a question of walking the tree, using the dot notation for
child elements. Elements that appear multiple times form a collection that can be accessed
with an index in the normal way. The contrast in both size and complexity between the
Groovy version and the Java version is clear.
The next listing demonstrates working with the XML file.
Listing B.5. Slurping XML
String fileName = 'books.xml'
def books = new XmlSlurper().parse(fileName)
assert books.book.size() == 4
assert books.book[0].title == "Groovy in Action"
assert books.book.find {
it.@isbn == "9781935182948"
}.title == "Making Java Groovy"
def prices = []
books.book.price.each {
prices << it.toDouble()
}
assert prices == [39.99, 35.99, 35.99, 27.50]
assert prices.sum() == 139.47
Groovy uses two different classes for working with XML. The previous example used an
XmlSlurper . Groovy also includes an XmlParser . The XmlParser creates a tree of
Node instances, so if you need to approach the file from a node point of view, use the pars-
Search WWH ::




Custom Search