【发布时间】:2020-03-15 05:23:29
【问题描述】:
我试图将 XML 文档的字符串表示形式转换为 org.w3c.dom.Document 对象,但是在尝试解析字符串时,当我调用时得到一个空的节点列表集合:NodeList nodeList = document.getElementsByTagName("wb:data");
下面是一个独立运行的完整示例。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class App
{
public static void main( String[] args )
{
String query_url = "https://api.worldbank.org/v2/country/ARB/indicator/SP.POP.TOTL?date=2015:2018";
try {
URL url = new URL(query_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(25000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.connect();
InputStreamReader ins = new InputStreamReader(conn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(ins);
StringBuilder content = new StringBuilder();
String line;
int index=0;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null)
{
if (index++ == 0) continue;
content.append(line + "\n");
}
bufferedReader.close();
// parsing the JSON output, extracting all the population information belonging
// to a country
String response = content.toString();
try
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new InputSource(new StringReader(response)));
NodeList nodeList = document.getElementsByTagName("wb:data");
Node test = nodeList.item(0);
} catch (Exception e) {
e.printStackTrace();
}
return;
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}
我希望能够在 xml 文档中找到代表元素的节点,但得到了一个空的 nodeList。
【问题讨论】:
-
将命名空间前缀传递给
getElementsByName()将不起作用。前缀不是元素名称的一部分。 -
您是否尝试更改为
document.getElementsByTagName("data")?wb是元素的前缀。 -
我当时刚试了一下,目前没什么区别。
-
链接的副本将为您提供帮助。另外,没有理由构建
String,您可以将conn.getInputStream()的返回值直接传递给DocumentBuilder.parse()