View Category
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
groovy
printf '$%.2f\n', new XmlSlurper().parseText(xml).item.collect{
it.@quantity.toInteger() * it.@price.toFloat()
}.sum()

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
groovy
b = new groovy.xml.MarkupBuilder()
b.shopping {
csv.eachLine { line ->
(n, q, p) = line.split(',')
item(name:n, quantity:q, price:p)
}
}
// Groovy equivalent of Java JAXB solution
@XmlAccessorType(NONE)
class Item {
@XmlAttribute String name
@XmlAttribute Integer quantity
@XmlAttribute Double price
}

@XmlAccessorType(NONE)
@XmlRootElement
class Shopping {
@XmlElement Set<Item> items = []
}

Shopping shopping = new Shopping()
csvtext.eachLine{ line ->
(n, q, p) = line.split(',')
shopping.items << new Item(name:n, quantity:q.toInteger(), price:p.toDouble())
}
JAXB.marshal shopping, System.out