Java Reference
In-Depth Information
</book>
All done.
Note that here you get a handle on the Book class instance and pass that to the JAXBContext
to create your context for marshaling. There is an alternative way to create the context, which
requires you to pass a string to the constructor indicating the name of the package containing
the types you're working with.
For simplicity in Example 3-9 , you print to the console. Let's look at some drop-in replace-
ments for the output destination of the marshaling line of code. The marshaling, or what is
produced, is identical in every case; it is only whereit gets produced that you're changing.
Example3-9.Marshal to a DOM node
//Create Document
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
//Send marshal result to Document
m.marshal(book, doc);
//Find a value
String title = doc.getDocumentElement().
getElementsByTagName("title").item(0).getTextContent();
System.console().printf("Read %s now!", title);
/*
Prints: Read Of Grammatology now!
All done.
*/
Sometimes you want to marshal an object to XML and directly write out the result to a file.
This is shown in Example 3-10 . It's just like Example 3-9 , with a slight modification.
Example3-10.Marshal to a new file
m.marshal(book, new FileOutputStream(new File("aBook.xml")));
This creates a new file on the filesystem in the current directory.
Search WWH ::




Custom Search