首页 > 解决方案 > 子节点的标签可以与根节点相同吗?

问题描述

我被困在一项任务中,我必须从 API 的 XML 响应中读取数据。根节点和所有子节点具有相同的标记。例如。

<a //some attributes>
      <a>
        <element1>value1</element1>
        <element2>value2<element2>
      </a>
      <a>
        <element1>value3</element1>
        <element2>value4<element2>
      </a>
</a>

java代码如下:.

if (format == "xml") {
    try {

    URL url = new URL("https://api.worldbank.org/v2/country/" + cc + "/indicator/" + ic + "?scale=y&format=" + format + "&date=" + start + ":" + end);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    String response1 = response.toString();

    response1 = response1.substring(1); //resolving problem in API response. referred https://stackoverflow.com/questions/11577420/fatal-error-11-content-is-not-allowed-in-prolog for error
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(new StringReader(response1)));


    NodeList Node = doc.getElementsByTagName("wb:data");

    if (Node.getLength() > 0) {
        Element ele = (Element)Node.item(0);
        NodeList Node2=(NodeList) doc.getChildNodes();
        boolean flag=false;
        String spage_total=ele.getAttribute("pages");

        int page_total=Integer.parseInt(spage_total);
        String scount=ele.getAttribute("per_page");

        int count=Integer.parseInt(scount);
        String stotal=ele.getAttribute("total");

        int total=Integer.parseInt(stotal);
        if (total < count) count = total;
        if(Node2.getLength()>0){
        Element ele2 = (Element)Node2.item(0);
        String svalue=ele2.getElementsByTagName("wb:date").toString();
        System.out.println(svalue);//this is where it says com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl@6b1274d2
    }}
} catch (Exception e) {
    System.out.println(e);
}

}

. .

我的问题是,是否可以从这样的 XML 中读取数据?

标签: javaxml

解决方案


推荐阅读