views:

501

answers:

3

This must be a newbie question, but I could not get it from http://xstream.codehaus.org.

Well, I have the following xml string

<cat age="4" >
   <name>Garfield</name>
</cat>

which needs to be mapped to:

class Cat {
  int age;
  String name;
}

Is there a simple way to do that using XStream? If not, what else could I try?

Thanks in advance.

A: 

You could use XPath.

Its very fast on modern JVMs and a transferable skill. E.g. you can use XPath on .NET etc

Fortyrunner
A: 

Actually, there is an answer on the XStream site -- in the Converter tutorial ;)

From http://xstream.codehaus.org/converter-tutorial.html:

    public Object unmarshal(HierarchicalStreamReader reader,
                    UnmarshallingContext context) {
            Birthday birthday = new Birthday();
            if (reader.getAttribute("gender").charAt(0) == 'm') {
                    birthday.setGenderMale();
            } else {
                    birthday.setGenderFemale();
            }
            reader.moveDown();
            Person person = (Person)context.convertAnother(birthday, Person.class);
            birthday.setPerson(person);
            reader.moveUp();
            reader.moveDown();
            Calendar date = (Calendar)context.convertAnother(birthday, Calendar.class);
            birthday.setDate(date);
            reader.moveUp();
            return birthday;
    }

(It's in the very last example/code block on the page.)

HTH

EDIT: Just wanted to add that you'll want to go through that whole tutorial, and not just seek out that code block. You'll need to create your own converter and register it with your XStream instance. (Probably obvious, but just in case...)

MCory
+2  A: 

Annotate your class like so (check http://xstream.codehaus.org/annotations-tutorial.html for details):

@XStreamAlias("cat")
class Cat {
  @XStreamAsAttribute
  int age;
  String name;
}

Now just use XStream as follows:

xstream = new XStream();
xstream.processAnnotations(Cat.class);
Cat roundtripGarfield = (Cat)xstream.fromXML(xstream.toXML(garfield));
Christopher Oezbek
Was just writing the same thing.Add a link to the annotations docs: http://xstream.codehaus.org/annotations-tutorial.html
daveb
@daveb: thanks for the hint
Christopher Oezbek
+1 It completely slipped my mind that there'd be an annotation for that. Should've thunk...
MCory
@MCory: No problem ;-) If you understand unmarshal you might be able to solve the question in http://stackoverflow.com/questions/2045290/xstream-collapsing-xml-hierarchy-as-i-parse which I would find interesting to see answered as well.
Christopher Oezbek
Thanks Christopher -- I appreciate the tip (and feel free to check the answer to see if it's worth anything; already posted it).
MCory
Thanks for the tips, by the way, without annotations xstream.aliasAttribute(Cat.class, "age", "age") also worked for me.
anonymous