Java XStream - Ignore tag that doesn't exist in XML

Qwan picture Qwan · Dec 10, 2010 · Viewed 8k times · Source

I currently use a piece of XML like the following

<Person>
    <Name>Frank Smith</Name>
    <Id>100023412</Id>
    <DOB>12/05/1954</DOB>
    <LasLogin>01/09/2010</LasLogin>
    <FavOS>Windows</FavOS>      // Wild card that may occasionally appear
</Person>

What I am stuck with, is when using XStream I need to be able to ignore certain tags that appear (in the case above 'FavOS') These tags may not be known or change in the future. Is there a way to Ignore all tags that do not match what is currently implemented?

(Using XStream 1.3.1)

Answer

markthegrea picture markthegrea · Jan 4, 2011

As it took me more than 15 minutes to find this answer, I thought I would post it.

XStream xstream = new XStream(new DomDriver()) {
            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {
                    public boolean shouldSerializeMember(Class definedIn, String fieldName) {
                        try {
                            return definedIn != Object.class || realClass(fieldName) != null;
                        } catch(CannotResolveClassException cnrce) {
                            return false;
                        }
                    }
                };
            }
        };

This seems to skip xml items that are not in your objects.