6.8. Customizing XML Generated from an Object
Problem
You are trying to create an XML document from a Java object, and you want to customize the layout and structure of the generated XML document.
Solution
Use a Betwixt mapping file to customize the output of the
BeanWriter. Below is an example of a mapping file
for the Play class, which was introduced in
Recipe 6.2. When Betwixt serializes or deserializes
an object to or from XML, it will search for a resource,
<classname>.betwixt, in the same package
as the class to be written or read. The following XML
document—Play.betwixt—is stored in
the same package as the Play class, and it
customizes the XML output from Betwixt:
<info primitiveTypes="element">
<element name="play">
<attribute name="genre" property="genre"/>
<attribute name="year" property="year"/>
<attribute name="language" property="language"/>
<addDefaults/>
</element>
</info>This file tells Betwixt that genre,
year, and language shall be
stored as XML attributes, and that the remaining bean properties are
to be written as XML elements. The following code is used to create a
customized XML document from an instance of Play:
import org.apache.commons.betwixt.io;
Play play = (Play) plays.get(0);
BeanWriter beanWriter = new BeanWriter( );
beanWriter.enablePrettyPrint( );
beanWriter.write( play );
logger.debug( beanWriter.toString( ) );Betwixt creates the following XML document, which stores the
genre, year, and
language properties as attributes of the
play element. The ...
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