2011-04-03 96 views
2

當我試圖從我的servlet的doGet方法訪問我的xml數據時,它只輸出值到白色空格,包括整個值。java dom getTextContent()問題

XML文件:

<RealEstate> 
    <Property> 
      <Type>Apartment</Type> 
      <Bedrooms>2</Bedrooms> 
      <Bathrooms>2</Bathrooms> 
      <Suburb>Bondi Junction</Suburb> 
      <Rent>1000</Rent> 
    </Property> 
</RealEstate> 

我再打電話從Java Servlet中的郊區doGet

Node suburb1 = doc.getElementsByTagName("Suburb").item(i); 
out.println("<tr><td>Suburb</td>" + "<td>"+suburb1.getTextContent()+"</td></tr>"); 

而且只輸出 「邦迪」,而不是 「邦迪結」

有人知道爲什麼嗎?

回答

2

嘗試迭代suburb1的子節點和所有包含文本節點的串聯值。在大多數DOM實現中,getTextContent()方法非常成問題。它很少做開發人員認爲它應該做的事情。

4

我試過你的代碼,你的xml,它打印出我的整個文本內容,很奇怪。無論如何,Node#getTextContext方法返回當前節點及其後代的文本內容。 我建議你使用node.getFirstChild().getNodeValue(),它打印出你節點的文本內容,而不是其後代。另一種方法是遍歷Suburbs節點的子節點。 你也應該看看here

這是我的主要打印出兩次相同的文字,同時使用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("<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>