java dom getTextContent()问题

当我试图从我的servlet的doGet方法访问我的xml数据时,它只输出值到白色空格,包括整个值。

XML文件:

   Apartment 2 2 Bondi Junction 1000   

然后我从doGet的Java Servlet调用Suburb:

 Node suburb1 = doc.getElementsByTagName("Suburb").item(i); out.println("Suburb" + ""+suburb1.getTextContent()+""); 

它只输出“邦迪”而不是“邦迪交界”

有人知道为什么吗?

我已经用你的xml尝试了你的代码,它为我打印出整个文本内容,非常奇怪。 无论如何, Node#getTextContext方法返回当前节点及其后代的文本内容。 我建议你使用node.getFirstChild().getNodeValue() ,它打印出你的节点而不是它的后代的文本内容。 另一种方法是迭代Suburbs节点的子节点。 你也应该看看这里 。

这是我的主要打印两次相同的文本,使用getFirstChild().getNodeValue()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("Suburb" + ""+node.getFirstChild().getNodeValue()+""); 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("Suburb" + "" + textBuilder.toString() + ""); } } } 

这是我的xml输出:

 SuburbBondi Junction SuburbBondi Junction 

尝试迭代suburb1的子节点和所有包含的文本节点的连接值。 getTextContent()方法在大多数DOM实现中都很成问题。 很少有开发人员认为它应该做的事情。