DOMで作成し、xpathで照会した文字列を保存する際に問題が発生します。これが私のコードGoogleとサンプルで使用したいくつかのリファレンスです
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");
tryandcatchブロック内で出力されているようですが、メソッドを取得してシステムの印刷を実行しようとすると、次のようになります。
public static void main (String[] args) {
try {
System.out.println(getRoute());
} catch (Exception e) {
System.out.println(e);
}
}
文字列全体ではなく、出力の最後の行しか取得できませんでした。