Search code examples
javaparsingxml-parsingxstream

Parse changing XML using XStream


I am receiving an XML response from a server. But response is changing according to my request. I want to parse XML response using XStream Parser. While converting from XML to POJOs , I am getting exceptions of "unrecognized fields". I only want some fields during conversion and ignore the rest. For example: My Pojo class is:

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


Solution

  • Set XStream to ignore unknown elements: 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);
        }
    }