【问题标题】:Passing a stringbuilder to a doc将字符串生成器传递给文档
【发布时间】:2015-12-08 21:53:05
【问题描述】:

我有以下代码

private void getdata(String stringfromDate,String stringtoDate ) throws IOException {
StringBuilder retVal = new StringBuilder();
URL oracle = new URL("https://xxxxxxxxxxxxxxxx" + stringfromDate +"&ToDate=" + stringtoDate +"" );
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));

String newLine = "\n";
String inputLine;
while ((inputLine = in.readLine()) != null) {
            //System.out.println(inputLine);
retVal.append(inputLine).append(newLine);

}

in.close();

passSting(retVal);

    }

private void passSting(StringBuilder retVal) {
Document doc = null;
try {
doc = loadXMLFromString(retVal.toString());//pull in the XML data into a new doc
System.out.println(doc);
} catch (Exception ex) {
Logger.getLogger(JavaApplication63.class.getName()).log(Level.SEVERE, null, ex);
}
    }

public static org.w3c.dom.Document loadXMLFromString(String xml) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}   

我通过 retVal 传递给一个方法,以便我可以创建一个可以作为 XML 文档读取的文档,但是文档值似乎为 null 我做错了什么?这就是我在控制台窗口中得到的 [#document: null]

【问题讨论】:

  • 您确定StringBuilder 中有内容吗?你在while 中有一个打印语句,所以我假设你测试了那部分。
  • 是的,如果我将鼠标悬停在 retVal.toString() 上方,我会看到预期的数据……只是文档显示为空……
  • 如果在创建builder 之前添加factory.setNamespaceAware(true); 怎么样。
  • @gonzo doc 仍然显示为 null,但是我已经询问了 doc,发现 fNodeValue 包含数据..即使 doc 本身显示为 null...这有什么用吗?
  • 进一步询问显示 fNodeName 包含数据项标签。

标签: java xml stringbuilder doc


【解决方案1】:

org.w3c.dom.Document#toString 方法返回null。然而,实际对象不是null。如果在解析String 后打印doc==null,您应该会看到它返回false 而不是true。希望这可以帮助。

【讨论】:

  • @gonzo,那么我应该怎么做才能使内容显示在 doc 中,因为 doc 被传递给一个 populate 方法,该方法获取每个 并将它们分开。
  • @MrAssistance 数据仍在您的 doc 对象中,您只是不像当前那样访问数据。您需要使用doc 的API。尝试做类似doc.getDocumentElement().getTextContent()
  • 是的,这似乎可以为我提供所有文本内容,我将使用什么来获取像 data 这样的数据
  • @MrAssistance 您是否从 cmets 中查看了该链接?所有API 都在里面。或者如果你想要更多的东西official。甚至在SO 中进行快速搜索
猜你喜欢
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 2011-09-18
  • 2022-11-26
  • 2019-06-19
  • 2012-06-13
  • 2020-04-08
  • 2016-06-01
相关资源
最近更新 更多