Я застрял в задании, где мне нужно прочитать данные из ответа XML API. Узел root и все дочерние узлы имеют одинаковый тег. Например.
<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?