Dealing with unmapped fields in XStream

Written on July 30, 2008 – 11:10 am | by mpayne

There is a jira patch proposed here for handling XML.  However that patch still needs to mature(see limitations) and gain acceptances. 

What might not be obvious(a.k.a poorly documented), is that stock XStream already has the
capability to handling this for many use cases.
The test class com.thoughtworks.acceptance.CustomMapperTest
Contains a method that demonstrates such an example.

   public void testCanBeUsedToOmitUnexpectedElements() {
        String expectedXml = “” +
                “<software>\n” +
                “  <version>1.0</version>\n” +
                “  <vendor>Joe</vendor>\n” +
                “  <name>XStream</name>\n” +

        xstream = new XStream() {

            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {

                    public boolean shouldSerializeMember(Class definedIn, String fieldName) {
                        return definedIn != Object.class ? super.shouldSerializeMember(definedIn, fieldName) : false;
        xstream.alias(”software”, Software.class);

        Software out = (Software) xstream.fromXML(expectedXml);
        assertEquals(”Joe”, out.vendor);

In the example above the Software class consists of properties.

    public String vendor;
    public String name;

Without the “MapperWrapper” the xml node “<version>1.0</version>” would generate an exception.

Post a Comment