当XML中有更多字段时,xStream崩溃

时间:2012-05-31 14:43:13

标签: java xml xml-serialization xstream

XSTREAM

当我有以下XML代码时:

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

我用Java代码读到这一切一切正常,但是当XML发生变化时,例如:

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

我收到错误,但我希望程序不会停止,并且不要使用现场测试。有没有办法处理这个异常,而程序不会停止?

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

2 个答案:

答案 0 :(得分:5)

XStream 1.4.5使您可以轻松处理未知标记。对于尚未实现或已被删除且您正在处理旧xml的标记,请使用ignoreUnknownElements。

  

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

您还可以指定要忽略的特定标记。

答案 1 :(得分:0)

感谢Brian Agnew,我找到了答案,这就是解决方案:

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