在我的应用程序中,我通过HTTP使用一些API,它返回响应为xml。我想自动将数据从xml绑定到bean。
例如,绑定xml:
<xml>
<userid>123456</userid>
<uuid>123456</uuid>
</xml>
到这个bean(也许是在注释的帮助下)
class APIResponce implement Serializable{
private Integer userid;
private Integer uuid;
....
}
最简单的方法是什么?
答案 0 :(得分:5)
我同意使用JAXB。由于JAXB是一个规范,您可以从多个实现中进行选择:
以下是使用JAXB的方法:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class APIResponce {
private Integer userid;
private Integer uuid;
}
与以下演示课程一起使用时:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(APIResponce.class);
File xml = new File("input.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
APIResponce api = (APIResponce) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(api, System.out);
}
}
将生成以下XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xml>
<userid>123456</userid>
<uuid>123456</uuid>
</xml>
答案 1 :(得分:4)
尝试JAXB - http://jaxb.java.net/
它的介绍文章http://www.javaworld.com/javaworld/jw-06-2006/jw-0626-jaxb.html
答案 2 :(得分:1)
作为Castor和JAXB的替代方案,Apache还有一个用于对象绑定的XML项目:
答案 3 :(得分:1)