1

我编写了一个 java web 服务客户端程序,它调用一个以国家名称作为输入参数的方法,并将城市名称作为 XML 格式的字符串返回。

返回并存储在 String 变量中的示例 XML 如下所示。

<NewDataSet>
  <Table>
    <Country>British Indian Ocean Territory</Country>
    <City>Diego Garcia</City>
  </Table>
  <Table>
    <Country>India</Country>
    <City>Ahmadabad</City>
  </Table>
  ......
</NewDataSet>

任何人都可以帮助我如何将存储在String变量中的这个 xml 转换为 Cities.java bean,它有两个访问器CountryCity.

谢谢你,普拉塔普。

4

3 回答 3

2

您应该使用JAXB来完成此任务,它是用于将 XML 文件转换为对象的 Java 标准。

StringReader reader = new StringReader(xmlString);
JAXBContext jaxbContext = JAXBContext.newInstance(Cities.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Cities response = (Cities) unmarshaller.unmarshal(reader);

您还需要像这样注释您的 Cities 类

@XmlRootElement
public class Cities {

    @XmlElement
    private String coutry;

    @XmlElement
    private String city;

    //setters and getters

}

这应该适合你。您还可以使用@XmlElement(name="")自定义将 XML 元素绑定到 Java 属性。

于 2013-09-03T07:59:37.843 回答
1

您可以使用 JAXB 创建 XML 文件的对象表示。这里的“NewDataSet”元素包含一个子(表)元素列表。使用 JAXB,您可以创建一个“NewDataSet”实例,该实例又包含一个“Table”对象列表。然后您可以遍历列表以获取每个“表”的“国家”和“城市”的值。您可以这样做:

这将代表 XML 的“表”元素。

@XmlRootElement
public class Table {
private String country;
private String city;

// getters and setters
}

这是您的“NewDataSet”,其中包含“表”元素列表:

@XmlRootElement
public class NewDataSet {
private List<Table> tableList;

public List<Table> getTableList() {
    return tableList;
}

    @XmlElementWrapper(name = "NewDataSet")
    @XmlElement(name = "Table")
    public void setCustomerList(List<Table> tableList) {
        this.tableList =tableList;
    }
}

现在使用 JAXB unmarshaller,您可以创建“NewDataSet”的实例:

JAXBContext jaxbContext = JAXBContext.newInstance(NewDataSet.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("your xml as string");
NewDataSet newDataSet = (NewDataSet) unmarshaller.unmarshal(reader);

参考:用于 XML 绑定的 Java 架构 (JAXB)

于 2013-09-03T08:21:40.550 回答
0

您可以使用 XMLBeans 库来解析 XML。

http://xmlbeans.apache.org/documentation/tutorial_getstarted.html

于 2013-09-03T08:13:06.913 回答