Skip to main content

@Xml Attribute Formats

The attribute-oriented XmlFormat values move bean-property values between XML attributes and child elements:

  • XmlFormat.ATTR promotes a single property to an attribute.
  • XmlFormat.ATTRS makes a whole bean render its properties as attributes, or lets a single Map property contribute arbitrary attributes.
  • XmlFormat.ELEMENT forces a property back to a child element, overriding an ATTRS default applied to the class.

Rendering a property as an attribute — ATTR​

The XmlFormat.ATTR format can be applied to bean properties to serialize them as XML attributes instead of elements. Note that this only supports properties of simple types (e.g. strings, numbers, booleans).

Data typeJSON exampleWithout annotationWith annotation
class MyBean {
@Xml(format=XmlFormat.ATTR)
public String a;
}
{
a: 'foo'
}
<object>
<a>foo</a>
</object>
<object a='foo'/>

Rendering all properties as attributes — ATTRS​

The XmlFormat.ATTRS format can be applied to bean classes to force all bean properties to be serialized as XML attributes instead of child elements.

Data typeJSON exampleWithout annotationWith annotation
@Xml(format=XmlFormat.ATTRS)
class MyBean {
public String a;
public int b;
}
{
a: 'foo',
b: 123
}
<object>
<a>foo</a>
<b>123</b>
</object>
<object a='foo' b='123'/>

Overriding the class default — ELEMENT​

The XmlFormat.ELEMENT format can be applied to bean properties to override the XmlFormat.ATTRS format applied on the bean class.

Data typeJSON exampleWithout annotationWith annotation
@Xml(format=XmlFormat.ATTRS)
class MyBean {
public String a;
@Xml(format=XmlFormat.ELEMENT)
public int b;
}
{
a: 'foo',
b: 123
}
<object>
<a>foo</a>
<b>123</b>
</object>
<object a='foo'>
<b>123</b>
</object>

Arbitrary attributes from a Map — ATTRS​

The XmlFormat.ATTRS format can also be applied to a single bean property of type Map to denote arbitrary XML attribute values on the element. These can be mixed with other XmlFormat.ATTR annotated properties but there must not be an overlap in bean property names and map keys.

Data typeJSON exampleWithout annotationWith annotation
class MyBean {
@Xml(format=XmlFormat.ATTRS)
public Map<String,Object> a;
@Xml(format=XmlFormat.ATTR)
public int b;
}
{
a: {
k1: 'foo',
k2: 123
},
b: 456
}
<object>
<a>
<k1>foo</k1>
<k2 _type='number'>123</k2>
</a>
<b>456</b>
</object>
<object k1='foo' k2='123' b='456'/>

See also​