java - 子节点的标签可以与根节点相同吗?
问题描述
我被困在一项任务中,我必须从 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 中读取数据?
解决方案
推荐阅读
- sql - 如何从最后一个父级的行中获取数据
- c - 如何在 switch 语句中评估案例 (C)
- backend - 实时 API 托管建议和架构设计建议
- node.js - npm 错误!errno fetch_error 角度
- tensorflow - AutoML Vision Edge 中使用什么算法?
- hibernate - 查询参数与 quarkus 上的结果不一致
- python - 如何使用 M1 在 MacOS 上安装 SciPy
- scala - Akka committableOffset 存储在数据库中
- python - 用 astropy 和 fit_wcs_from_points 拟合天顶等面积投影
- arrays - bash - 使用带有 find 命令的数组