Java Reference
In-Depth Information
a.setLastName("Derrida");
book.setAuthor(a);
book.setPrice(39.95);
book.setTitle("Glas");
book.setCategory(Category.PHILOSOPHY);
//Put the topic into XML
XMLStreamRoundTrip<Book> x = new XMLStreamRoundTrip<Book>();
String bookXml = x.toXml(book);
//Print entire XML
System.console().printf("XML:\n%s\n", bookXml);
//Create a new object by rehydrating the XML
Book newBook = x.fromXml(bookXml);
//Show values
System.console().printf("Object:\n%s costs $%s\n",
newBook.getTitle(), newBook.getPrice());
}
public String toXml(T model) {
return new XStream().toXML(model);
}
@SuppressWarnings("unchecked")
public T fromXml(String modelAsString) {
XStream xstream = new XStream(new DomDriver());
T model = (T)xstream.fromXML(modelAsString);
return model;
}
}
This couldn't be easier. Most of the code is setting up the topic object itself. The two methods
at the bottom of the class do all of the XStream work. The output is just as you would expect:
XML:
<com.soacookbook.ch02.xstream.Book>
<title>Glas</title>
<price>39.95</price>
<author>
<firstName>Jacques</firstName>
<lastName>Derrida</lastName>
</author>
<category>PHILOSOPHY</category>
</com.soacookbook.ch02.xstream.Book>
Search WWH ::




Custom Search