Java Reference
In-Depth Information
Converting an XML Document Instance into a Java
Object
Problem
You have an XML document instance that you want to convert into a Java object.
Solution
Use JAXB's Unmarshaller class with a JAXBElement<T> .
With JAXBElement<T> , you can specify the class into which you want to unmarshal your
XML content without having to first write any mapping. That is, you don't have to use an-
notations on your XML files during unmarshaling when you use JAXBElement and indicate
the class of the object you want your result in as its type parameter.
You may get XML from a variety of sources, not just objects that were first marshaled from
JAXB, or that you had an opportunity to annotate. You might want to allow a fairly loose in-
terpretation of your object structure that, for example, allows your root element name to be
specified differently than it is in the actual class.
XStream produces a root element in the XML serialization process that prepends the package
name. So instead of serializing your Book object into a <book> element, you end up with a
root element of <com.soacookbook.ch02.xstream.Book> . So while you and I know that
XML document would “fit” into a Book object, it's hard for the tools that actually do the work
to know that. Luckily, the tools are pretty smart.
NOTE
There is a distinction between serialization and marshaling. The term “serialization” is used to ex-
press the simple transformation of an object into an output stream, which here happens to be an XML
format. Marshaling, which also produces an XML format, does its work specifically through binding,
which is achieved in JAXB in the form of annotation mappings.
Example 3-12 uses JAXBElement<T> to unmarshal an XML document that was generated en-
tirely outside of JAXB. No XML annotations are used here; this Book is just a POJO. Plus,
you didn't even use JAXB to do the marshaling in the first place; you used XStream.
Example3-12.Using JAXBElement<T> to unmarshal an XML string
Search WWH ::




Custom Search