Java Reference
In-Depth Information
package com.soacookbook.ch02.jaxb;
import static java.lang.System.out;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class MarshalToConsole {
public static void main(String...arg) {
try {
Book book = new Book();
Author a = new Author();
a.setFirstName("Jacques");
a.setLastName("Derrida");
book.setAuthor(a);
book.setPrice(34.95);
book.setTitle("Of Grammatology");
book.setCategory(Category.PHILOSOPHY);
Class[] c = {Book.class};
JAXBContext ctx = JAXBContext.newInstance(c);
Marshaller m = ctx.createMarshaller();
//could also use System.out here
m.marshal(book, out);
out.println("\nAll done.");
} catch (JAXBException ex) {
ex.printStackTrace();
}
}
}
Here is the result printed to the console (I added spacing and line breaks for readability):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
<author>
<firstName>Jacques</firstName>
<lastName>Derrida</lastName>
</author>
<category>PHILOSOPHY</category>
<price>34.95</price>
<title>Of Grammatology</title>
Search WWH ::




Custom Search