开发者

XStream: How do I map xml mixed attributes and elements to POJOs?

This must be a newbie question, but I could not get it from http://x-stream.github.io/.

Well, I have t开发者_运维知识库he 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.


Annotate your class like so (check http://x-stream.github.io/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));


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

From http://x-stream.github.io/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...)


You could use XPath.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜