Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

This example assumes the following class is already on your CLASSPATH:

Include Page
XML Example
XML Example

Here is an example of using XmlParser:

Code Block
def records = new XmlParser().parseText(XmlExamples.CAR_RECORDS)
def allRecords =
assert allRecords == 3
def allNodes = records.depthFirst().size()
assert allNodes == 10
def firstRecord =[0]
assert 'car' ==
assert 'Holden' == firstRecord.'@make'
assert 'Australia' ==
// 2 cars have an 'e' in the make
assert 2 =={ it.'@make'.contains('e') }.size()
// makes of cars that have an 's' followed by an 'a' in the country
assert ['Holden', 'Peel'] =={ =~ '.*s.*a.*' }.'@make'
// types of records
assert ['speed', 'size', 'price'] == records.depthFirst().grep{ it.'@type' }.'@type'
// update to show what would happen if 'New Zealand' bought Holden[0].value = ['New Zealand']
assert 'New Zealand' ==
// names of cars with records sorted by year
assert ['Royale', 'P50', 'HSV Maloo'] =={ it.'@year'.toInteger() }.'@name'

It is also possible to parse XML documents using namespaces:

Code Block
def ns = new groovy.xml.Namespace("", 'ns')
def root = new XmlParser().parseText("...")
def authors = root[][]