6.9. Turning XML Documents into Beans
Problem
You need to convert an XML document into a Bean.
Solution
Use Betwixt’s BeanReader to parse
an XML document and create an instance of the appropriate bean.
Register bean classes with the BeanReader, and
parse an XML document loaded from an InputStream,
InputSource, or Reader. The
following XML document will be parsed into the
Play and Character beans
introduced in Recipe 6.2:
<play genre="tragedy" year="1603" language="english">
<author>William Shakespeare</author>
<character protagonist="false">
<description>King of Denmark</description>
<name>Claudius</name>
</character>
<character protagonist="true">
<description>Son to the late, and nephew of the present king</description>
<name>Hamlet</name>
</character>
<character protagonist="false">
<description>friend to Hamlet</description>
<name>Horatio</name>
</character>
<name>Hamlet</name>
<summary>Prince of Denmark (Hamlet) freaks out, talks to father's ghost, and
finally dies in a duel.</summary>
</play>This XML document was created with BeanWriter,
using the customized format from Recipe 6.8.
To read this XML document with BeanReader, the
Play class will need to be registered with
BeanReader and the
XMLIntrospector must have the same settings as the
XMLIntrospector used when writing the document
with BeanWriter. The following code instantiates
and configures a BeanReader to read this
customized XML for the Play object:
import org.apache.commons.betwixt.io.BeanReader; InputStream customPlay ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access