rzch
rzch

Reputation: 95

JAXB: Convert Javabean Object to XML all properties as XML attributes rather than XML elements (node)

Currently I'm working on converting object to XML, I notice all object properties are listed as XML elements (node) unless you use @XmlAttribute on a particular getter or setting

Just wondering is there a way to automatically convert all object properties as XML attributes in JAXB.

Sample Code:

JAXBContext jc = JAXBContext.newInstance( foo.class );
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.setProperty(Marshaller.JAXB_FRAGMENT, true);
Foo foo = new foo();
foo.setType("type");
foo.setValue("value");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
m.marshal(foo, baos);

Upvotes: 1

Views: 865

Answers (3)

bdoughan
bdoughan

Reputation: 149017

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

There currently isn't a way to configure that by default simple properties should map to XML attributes. The following enhancement request has been filed for MOXy to add this behaviour.

  • Bug 333604 - Enhancement: Provide metadata to default simple properties to attributes (instead of elements)

Upvotes: 1

Thor
Thor

Reputation: 6656

If you are using JAXB for a complex schemata, it's a good idea to define the structure in a XSD:

<xsd:schema targetNamespace="http://myUri"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="parent">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element ref="child" maxOccurs="1"/>
        </xsd:sequence>
        <xsd:attribute name="id" type="xsd:long"/>
        <xsd:attribute name="name" type="xsd:string"/>
    </xsd:complexType>
</xsd:element>
<xsd:element name="child">
    <xsd:complexType>
        <xsd:attribute name="id" type="xsd:long"/>
        <xsd:attribute name="name" type="xsd:string"/>
        <xsd:attribute name="code" type="xsd:string"/>
    </xsd:complexType>
</xsd:element>

This can be compiled with jaxb-xjc to .java files and you will have the defined xsd:attributes as attributes in Java.

Upvotes: 0

manocha_ak
manocha_ak

Reputation: 902

have you tried using @XmlRootElement on the class top level?

Upvotes: 0

Related Questions