How to parse XML to java object using XStream

user709361 picture user709361 · Jan 6, 2012 · Viewed 10.7k times · Source

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>();
   }

Answer

Dan Hardiker picture Dan Hardiker · Jan 6, 2012

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)