【问题标题】:Converting from String to XML从字符串转换为 XML
【发布时间】: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()

标签: java xml rest


【解决方案1】:

请尝试使用以下代码。我能够解析并且能够获取国家/地区的信息。

try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new InputSource(new StringReader(response)));

        Element root = document.getDocumentElement();
        System.out.println(root.getNodeName());
        NodeList nodeList = document.getElementsByTagName(root.getNodeName());
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) node;
                System.out.println("Country Name : "  + eElement.getElementsByTagName("wb:country").item(0).getTextContent());
            }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 2012-10-10
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多