...
| Code Block |
|---|
// require(groupId:'com.thoughtworks.xstream', artifactId:'xstream', version:'1.2.2') // require(groupId:'xpp3', artifactId:'xpp3_min', version:'1.1.3.4.O') import com.thoughtworks.xstream.* class Staff { String firstname, lastname, position } def streamxstream = new XStream() def msgjohn = new Staff(firstname:'John', lastname:'Connor', position:'Resistance Leader') println streamxstream.toXML(msgjohn) |
This results in the following output:
| Code Block | ||
|---|---|---|
| ||
<Staff> <firstname>John</firstname> <lastname>Connor</lastname> <position>Resistance Leader</position> </Staff> |
Just as an aside, not related to annotations, here is how you could write the XML to a file:
| Code Block |
|---|
new File("john.xml").withOutputStream { out ->
xstream.toXML(john, out)
}
|
And how you would read it back in:
| Code Block |
|---|
// require(groupId:'com.thoughtworks.xstream', artifactId:'xstream', version:'1.3') // require(groupId:'xpp3', artifactId:'xpp3_min', version:'1.1.4c') import com.thoughtworks.xstream.* class Staff { String firstname, lastname, position } def xstream = new XStream() def john // now read back in new File("john.xml").withInputStream { ins -> john = xstream.fromXML(ins) } println john.dump() // => <Staff@12d96f2 firstname=John lastname=Connor position=Resistance Leader> |
Now, on to the annotations ...
XStream also allows you to have more control over the produced XML (in case you don't like its defaults). This can be done through API calls or with annotations. Here is how we can annotate our Groovy class with XStream annotations to alter the resulting XML:
...