Java JABX : Can I customize the output format?

Viewed 11

I have a standard Organization Java object which uses JAXB annotations, and I can do all the standard JAX stuff like marshalling and unmarshalling.

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
    name = "Organization"
)
public class Organization implements Serializable {
    @XmlElement(
        name = "LegalName"
    )
    protected String legalName;
    @XmlElement(
        name = "Id"
    )
    protected String id;
    @XmlElement(
        name = "Addresses"
    )
    protected Addresses addresses;

The object can be converted from an object

StringResult stringResult = new StringResult();
TransformerFactory.newInstance().newTransformer().transform(org, stringResult);
return stringResult.toString();

to a full XML representation easily

<Organization>
    <Id>1</Id>
    <LegalName>name</LegalName>
    <Addresses>
        <Address>1</Address>
        <Address>2</Address>
        <Address>3</Address>
    </Addresses>
</Organization>

I have a requirement to print a more conscise form of this object

Org {id}:{name}
- Addresses {count}: {Address1.id,Address2.id,Address3.id}

Is there any way I can leverage the existing transform functionality of the JAXB librarys, and define the template/logic in a plugable custom java class?

My initial thought is a 100% bespoke solution would involve a Object Wrapper and a dirty toString() method.

System.out.println(new MyObjectWrapper(org).toString());
0 Answers
Related