3

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

4 回答 4

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; 

}

与以下 Demo 类一起使用时:

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>
于 2010-09-16T19:19:42.920 回答
4

尝试 JAXB - http://jaxb.java.net/

它的介绍文章http://www.javaworld.com/javaworld/jw-06-2006/jw-0626-jaxb.html

于 2010-09-16T18:32:19.897 回答
1

作为 Castor 和 JAXB 的替代方案,Apache 也有一个将 XML 与对象绑定的项目:

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

于 2010-09-16T18:50:50.680 回答
1

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

这里有一个代码示例。

于 2010-09-16T20:15:19.053 回答