Search code examples
xmlxstream

How to make XStream skip unmapped tags when parsing XML?


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?


Solution

  • 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);
                }
            };
        }
    };