Reputation: 95
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
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.
Upvotes: 1
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