简体   繁体   English

使用XStream解析更改XML

[英]Parse changing XML using XStream

I am receiving an XML response from a server. 我从服务器收到XML响应。 But response is changing according to my request. 但是根据我的要求,反应正在发生变化。 I want to parse XML response using XStream Parser. 我想使用XStream Parser解析XML响应。 While converting from XML to POJOs , I am getting exceptions of "unrecognized fields". 在从XML转换为POJO时,我得到了“无法识别的字段”的例外。 I only want some fields during conversion and ignore the rest. 我只想在转换期间使用某些字段而忽略其余字段。 For example: My Pojo class is: 例如:我的Pojo类是:

    @XStreamAlias("Book")
    class Book{
        @XStreamAlias("author")
        private String author;

        @XStreamAlias("title")
        private String title;

        //getters and setters
   }

If my response is : 如果我的回答是:

<book>
  <author>ABC</author>
  <title>XYZ</title>
</book>

Conversion works fine. 转换工作正常。 But if my response is: 但如果我的回答是:

<book>
  <author>ABC</author>
  <title>XYZ</title>
  <pages>50</pages>
</book>

I am getting exceptions during conversion. 我在转换期间遇到异常。 How can I avoid such exceptions for unwanted fields? 如何避免不需要的字段的此类例外? Is there any way to tell XStream to avoid any other field which is not mentioned in POJO? 有没有办法告诉XStream避免POJO中没有提到的任何其他字段?

How do you instanciate XStream? 你如何实现XStream?

You could try with omitField() if you know the names of the fields to omit, or even better, read this resource. 如果您知道要省略的字段名称,或者甚至更好,请阅读此资源,您可以尝试使用omitField()
http://rafaelsteil.com/omit-unexpected-xml-elements-with-xstream/ http://rafaelsteil.com/omit-unexpected-xml-elements-with-xstream/

Set XStream to ignore unknown elements: xStream.ignoreUnknownElements() 设置XStream以忽略未知元素: xStream.ignoreUnknownElements()

@XStreamAlias("Book")
class Book {

    @XStreamAlias("author")
    String author;

    @XStreamAlias("title")
    String title;

    public static void main(String[] args) {
        String input = "<Book>"
                + "<author>ABC</author>"
                + "<title>XYZ</title>"
                + "<pages>50</pages>"
                + "</Book>";

        XStream xStream = new XStream();
        xStream.ignoreUnknownElements();
        xStream.processAnnotations(Book.class);

        Book book = (Book) xStream.fromXML(input);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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