Search code examples
javaxstream

How to parse XML to java object using XStream


i have some xml code, and i want to parse this to java object please help me.

   <Error>
    <number>1020</number>
    <Type>fatal</Type>
    <Text>Nagaraju</Text>
    <Text>Suresh</Text>
    <Text>Sound</Text>
    <Text>Rajesh</Text>
   </Error>

java object is

   Class Error{
      int number;
      String type;
      List<String>texts=new ArrayList<String>();
   }

Solution

  • I would map it manually personally, or use JAX-B perhaps, but if you really want to use XStream:

    1. You'll need to map the class Error to the element Error. You can do this with an "alias". http://x-stream.github.io/alias-tutorial.html
    2. The List isn't usually represented that way, it would normally be nested. Serialise your Error object out to XML to see what it would normally be represented as. If you want to do this way you'll likely need a convertor: http://x-stream.github.io/converter-tutorial.html
    3. You could also use implicit collections, by registering the Error and text element. http://x-stream.github.io/javadoc/com/thoughtworks/xstream/XStream.html#addImplicitCollection(java.lang.Class, java.lang.String, java.lang.Class)