XStream – Handling Attributes in XML

In the previous tutorial we saw how to convert Java to XML and back. In this tutorial we look at different ways to handle XML attributes using XStream. However note that the attributes are only safe if you know that the written String values are not affected by the XML parser’s white space normalization. The XML specification requires that a parser does this and it means that an attribute value of:

will always be normalized and passed this assertion:

XStream has no influence about this behavior.

Case 1 : Element with attributes but no value – Using SingleValueConverter

In this example we use a SingleValueConverter to convert the XML element containing an attribute. This method does not work if the element has a value

Case 2 : Element with attributes but no value – Using attribute alias

The same result can be obtained by using an attribute alias.

Case 3 : Element with attributes and value

If the element has an attribute as well as a value then we use a special Converter called ToAttributedValueConverter

Leave a Reply

Your email address will not be published. Required fields are marked *