Skip to main content

@Xml Element & Mixed Formats

The element-oriented XmlFormat values let a single property produce free-form or mixed child content:

Free-form child elements — FREEFORM​

The XmlFormat.FREEFORM format can be applied to a single bean property of either a simple type or array/Collection. It allows free-form child elements to be formed. All other properties on the bean MUST be serialized as attributes.

Data typeJSON exampleWith annotation
class MyBean {
@Xml(format=XmlFormat.ATTR)
public String a;
@Xml(format=XmlFormat.FREEFORM)
public String b;
}
{
a: 'foo',
b: 'bar'
}
<object a='foo'>
bar
</object>
class MyBean {
@Xml(format=XmlFormat.ATTR)
public String a;
@Xml(format=XmlFormat.FREEFORM)
public Object[] b;
}
{
a: 'foo',
b: ['bar', 'baz', 123, true, null]
}
<object a='foo'>
bar
baz
123
true
</object>

Mixed content — MIXED and MIXED_PWS​

The XmlFormat.MIXED format is similar to XmlFormat.FREEFORM except elements names on primitive types (string/number/boolean/null) are stripped from the output. This format particularly useful when combined with bean dictionaries to produce mixed content. The bean dictionary isn't used during serialization, but it is needed during parsing to resolve bean types. The XmlFormat.MIXED_PWS format identical to XmlFormat.MIXED except whitespace characters are preserved in the output.

Data typeJSON exampleWithout annotationsWith annotations
class MyBean {
@Xml(format=XmlFormat.MIXED)
@MarshalledProp(dictionary={MyBeanX.class, MyBeanY.class})
public Object[] a;
}

@Marshalled(typeName="X")
class MyBeanX {
@Xml(format=XmlFormat.ATTR)
public String b;
}

@Marshalled(typeName="Y")
class MyBeanY {
@Xml(format=XmlFormat.ATTR)
public String c;
}
{
a: [
'foo',
{ _type:'X', b:'bar' },
'baz',
{ _type:'Y', c:'qux' },
'quux'
]
}
<object>
<a>
<string>foo</string>
<object>
<b>bar</b>
</object>
<string>baz</string>
<object>
<c>qux</c>
</object>
<string>quux</string>
</a>
</object>
<object>
foo<X b='bar'/>baz<Y c='qux'/>quux
</object>

It should be noted that when using MIXED, you are not guaranteed to parse back the exact same content since side-by-side strings in the content will end up concatenated when parsed.

For a detailed treatment of how empty strings and whitespace are preserved (or lost) in MIXED and MIXED_PWS output, see Whitespace Handling.

See also​