Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

xstream

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)

like image 389
Qwan Avatar asked Dec 10 '10 14:12

Qwan


1 Answers

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.

like image 197
markthegrea Avatar answered Oct 12 '22 01:10

markthegrea