我在存储使用 DOM 构建并使用 xpath 查询的字符串时遇到问题。这是我在代码Google和Sample中使用的一些参考
public static String getRoute() throws Exception {
String xPathString = "//text() ";
String nodeString = "";
String notags = null;
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
//URL and HTTP connection here
InputStream inputXml = connection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inputXml);
NodeList nodes = (NodeList) xpath.evaluate(xPathString, doc, XPathConstants.NODESET);
for (int i = 0, n = nodes.getLength(); i < n; i++) {
nodeString = nodes.item(i).getTextContent();
notags = nodeString.replaceAll("<[^>]*>", "");
System.out.print(notags + "\n");
}
} catch (XPathExpressionException ex) {
System.out.print("XPath Error");
}
return notags;
该代码似乎System.out.print(notags + "\n");
在 try 和 catch 块中打印出来,但是当我尝试获取该方法并使用以下方法进行系统打印输出时:
public static void main (String[] args) {
try {
System.out.println(getRoute());
} catch (Exception e) {
System.out.println(e);
}
}
我只能得到输出的最后一行而不是整个字符串。