java 反序列化文档时如何忽略未使用的 XML 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4740934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:49:18  来源:igfitidea点击:

How to ignore unused XML elements while deserializing a document?

javaxml-deserializationsimple-framework

提问by Cristian

I'm using SimpleXml to (de)serialize POJOs. Now, I have a big XML which has some elements which are not needed. For instance, with this XML:

我正在使用 SimpleXml 来(反)序列化 POJO。现在,我有一个很大的 XML,其中包含一些不需要的元素。例如,使用此 XML:

<Root>
   <Element>Used</Element>
   <Another>Not used</Another>
<Root> 

I want to create a POJO which looks like:

我想创建一个如下所示的 POJO:

@Root
class Root{
    @Element
    private String element;
}

Problem is that I'm getting this Exception:

问题是我收到了这个异常:

simpleframework.xml.core.ElementException: Element 'Another' does not have a
match in class blah.blah.Blah at line 1

So... how should I configure the POJO so that I can parse the XML correctly?

那么...我应该如何配置 POJO 以便我可以正确解析 XML?

回答by dogbane

Set strictto false within the Root annotation to ignore any XML elements or attributes that do not appear in the class.

strict在 Root 注释中设置为 false 以忽略未出现在类中的任何 XML 元素或属性。

@Root(strict=false)

Alternatively, set strictto false when you read the xml in the serialiser:

或者strict序列化器中读取 xml 时设置 为 false :

Root root = serializer.read(Root.class, source, false);

回答by Daniele Giannini

you can add (required=false) to a single element

您可以将 (required=false) 添加到单个元素

@Element(required=false)
private int statusCode;

if you have more elements use

如果你有更多的元素使用

 @Root(strict=false)