简体   繁体   中英

xStream crashes when there are more fields in the XML

xStream

When I have the following XML code:

<xml>
  <version>1.1</version>
  <url>http://www.google.nl</url>
</xml>

And I read this with my Java code everything works fine, but when the XML changes, for example to:

<xml>
  <test>test</test>
  <version>1.1</version>
  <url>http://www.google.nl</url>
</xml>

I get an error, but I want that the program doesn't stop, and don't use the field test. Is there a way to handle this exception without that the program stops?

Exception in thread "main"         com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldExce    ption: No such field Version.iets
---- Debugging information ----
field               : iets
class               : Version
required-type       : Version
converter-type      :     com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path                : /Version/iets
line number         : 1
version             : null
-------------------------------

XStream 1.4.5 makes you simple to deal with unknown tags. Use ignoreUnknownElements for tags which are not implemented yet or has been removed and you are dealing with old xml.

http://x-stream.github.io/javadoc/com/thoughtworks/xstream/XStream.html#ignoreUnknownElements%28%29

You can also specify which particular tag you would like to ignore.

Thanks to Brian Agnew I found the answer, this is the solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM