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 ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.