How to ignore unused XML elements while deserializing a document?

半城伤御伤魂 提交于 2019-12-18 13:54:10

问题


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:

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

I want to create a POJO which looks like:

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


回答1:


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

@Root(strict=false)

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

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



回答2:


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

@Element(required=false)
private int statusCode;

if you have more elements use

 @Root(strict=false)


来源:https://stackoverflow.com/questions/4740934/how-to-ignore-unused-xml-elements-while-deserializing-a-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!