あなたのxmlであなたのコードを試してみましたが、テキストの内容全体が出力されました。非常に奇妙です。とにかく、このNode#getTextContext
メソッドは現在のノードとその子孫のテキスト コンテンツを返します。を使用することをお勧めしますnode.getFirstChild().getNodeValue()
。これは、ノードの子孫ではなく、ノードのテキスト コンテンツを出力します。もう 1 つの方法は、Suburbs ノードの子を反復処理することです。こちらもご覧ください。
getFirstChild().getNodeValue()
これは、 と の両方を使用して、同じテキストを 2 回出力する私のメインですgetChildNodes().item(i).getNodeValue()
。
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("dom.xml"));
NodeList nodeList = doc.getElementsByTagName("Suburb");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.hasChildNodes()) {
System.out.println("<tr><td>Suburb</td>" + "<td>"+node.getFirstChild().getNodeValue()+"</td></tr>");
NodeList textNodeList = node.getChildNodes();
StringBuilder textBuilder = new StringBuilder();
for (int j = 0; j < textNodeList.getLength(); j++) {
Node textNode = textNodeList.item(j);
if (textNode.getNodeType() == Node.TEXT_NODE) {
textBuilder.append(textNode.getNodeValue());
}
}
System.out.println("<tr><td>Suburb</td>" + "<td>" + textBuilder.toString() + "</td></tr>");
}
}
}
これはあなたのxmlでの私の出力です:
<tr><td>Suburb</td><td>Bondi Junction</td></tr>
<tr><td>Suburb</td><td>Bondi Junction</td></tr>