[英]XStream: How do I map xml mixed attributes and elements to POJOs?
这肯定是一个新手问题,但我无法从http://x-stream.github.io/获得。
好吧,我有以下xml字符串
<cat age="4" >
<name>Garfield</name>
</cat>
需要映射到:
class Cat {
int age;
String name;
}
是否有使用XStream做到这一点的简单方法? 如果没有,我还能尝试什么?
提前致谢。
像这样注释您的类(有关详细信息,请参见http://x-stream.github.io/annotations-tutorial.html ):
@XStreamAlias("cat")
class Cat {
@XStreamAsAttribute
int age;
String name;
}
现在只需按如下所示使用XStream:
xstream = new XStream();
xstream.processAnnotations(Cat.class);
Cat roundtripGarfield = (Cat)xstream.fromXML(xstream.toXML(garfield));
实际上,在XStream网站上有一个答案-在Converter教程中;)
来自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;
}
(在页面的最后一个示例/代码块中。)
高温超导
编辑:只是想补充一下,您将要遍历整个教程,而不仅仅是查找该代码块。 您需要创建自己的转换器并将其注册到XStream实例。 (可能很明显,但以防万一...)
您可以使用XPath。
它在现代JVM上非常快,并且具有可转让的技能。 例如,您可以在.NET等上使用XPath
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.