如何将xml绑定到bean

时间:2010-09-16 18:24:06

标签: java xml xml-binding

在我的应用程序中,我通过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;
....
}

最简单的方法是什么?

4 个答案:

答案 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)

答案 2 :(得分:1)

作为Castor和JAXB的替代方案,Apache还有一个用于对象绑定的XML项目:

Betwixt:http://commons.apache.org/betwixt/

答案 3 :(得分:1)

过去我使用XMLBeans将XML绑定到Java类型。它真的很容易使用。首先必须使用scomp命令(或maven插件等)将xml架构编译为Java类型,并使用代码中的类型。

行动here中有一个代码示例。