Search code examples
javaxmlxstream

Parse XML object in the context of another object in Xstrem


Let's say I have the following XML:

<people>
    <person name="John" id="1">...</person>
    .....
    <person name="Mark" id="3421">
        <father references="1" />
    </person>
</people>

And I have created the following Xstream object:

XStream configXstream = new XStream(new StaxDriver());
configXstream.alias("people", People.class);
configXstream.alias("person", Person.class);

I have parsed an existing XML to a People object. Now I want at runtime to add a person from an XML, and refer to its father which is in the existing People object. For example, I want to add the following:

<person name="Peter" id="3459">
    <father references="3421" />
</person>

Now I can't parse the XML to a person object because it says that the reference to the father is invalid.

Is there a way to tell xstream to parse an object given the context (the object from which it should resolve references?)


Solution

  • I ended up writing a custom converter which scans the list of people for a given id. To do that, I extended the Converter class and then registered it using xstream.registerConverter(new MyAwesomeCustomConverter).