How to make XStream skip unmapped tags when parsing XML?

Fixpoint picture Fixpoint · Mar 21, 2011 · Viewed 17.1k times · Source

I have a large XML document that I want to convert to a Java bean. It has a lot of tags and attributes, but I'm interested only in a handful of those. Unfurtounately, it seems that XStream forces you to declare a property in that bean for each and every tag that may ever be in that XML. Is there a way around this?

Answer

Somu picture Somu · Apr 22, 2011

Initialize XStream as shown below to ignore fields that are not defined in your bean.

XStream xstream = new XStream() {
    @Override
    protected MapperWrapper wrapMapper(MapperWrapper next) {
        return new MapperWrapper(next) {
            @Override
            public boolean shouldSerializeMember(Class definedIn, String fieldName) {
                if (definedIn == Object.class) {
                    return false;
                }
                return super.shouldSerializeMember(definedIn, fieldName);
            }
        };
    }
};