| Subcribe via RSS

ConversionException when parsing XML with XStream: Element is not defined

May 27th, 2009 Posted in Software Development

XStream is an easy to use Java library to serialize objects to XML and back again. Yesterday I wanted to parse a XML document generated by a third party software with the following structure:

<?xml version="1.0" encoding="UTF-8"?>
<AuditTrail>
    <Entry type="ExecutionReport" msgId="2544804979">
        <field tag="35" val="8"/>
        <field tag="34" val="000023"/>
        <field tag="43" val="N"/>
        <field tag="52" val="20090526-20:08:31"/>
        <field tag="6556" val="today12"/>
        <field tag="17" val="73740.1243368511.0"/>
        <field tag="32" val="*"/>
    </Entry>
    <Entry type="Acknowledged" msgId="1540251818">
    </Entry>
</AuditTrail>

I created three classes AuditTrail, AuditTrailEntry and AuditTrailEntryField for the elements AuditTrail, Entry, and field, respectively. In addition, I set the aliases accordingly:

XStream xStream = new XStream ();
xStream.alias ("AuditTrail", AuditTrail.class);
xStream.alias ("Entry", AuditTrailEntry.class);
xStream.alias ("field", AuditTrailEntryField.class);

A call to the method fromXml() of the XStream object resulted in the following exception:

ConversionException: Element [NAME] of type [TYPE]
                     is not defined as [NAME] in type [TYPE]

Because I did not find a quick solution via a Google search I was forced to read the XStream documentation. ;-) There I learned something about Implicit Collections in XStream. Whenever you have a collection which does not display it’s root tag, you can map it as an implicit collection:

xStream.addImplicitCollection (AuditTrailEntry.class, "fields");
xStream.addImplicitCollection (AuditTrail.class, "entries");

with

private List <AuditTrailEntryField> fields;

in class AuditTrailEntry and

private List <AuditTrailEntry> entries;

in class AuditTrail.

Leave a Reply