2013-07-12 77 views
0

我正在使用xPath獲取節點值。下面是我的XML如何使用XPath獲取節點以及節點值

<?xml version="1.0" encoding="UTF-8"?> 

<address> 
    <buildingnumber> 29 </buildingnumber> 
    <street> South Lasalle Street</street> 
    <city>Chicago</city> 
    <state>Illinois</state> 
    <zip>60603</zip> 
</address> 

這是我起訴

DocumentBuilder builder = tryDom.getDocumentBuilder(); 
Document xmlDocument = tryDom.getXmlDocument(builder, file); 

XPathFactory factory = XPathFactory.newInstance(); 
XPath xPath = factory.newXPath(); 

XPathExpression xPathExpression = null; 

String expression7 = "//address/descendant-or-self::*"; 

try { 

    xPathExpression = xPath.compile(expression7); 
    Object result = xPathExpression.evaluate(xmlDocument,XPathConstants.NODESET); 
    printXpathResult(result); 

} catch (XPathExpressionException e1) { 
    // TODO Auto-generated catch block 
    e1.printStackTrace(); 
} 

public static void printXpathResult(Object result){ 

    NodeList nodes = (NodeList) result; 

    for (int i = 0; i < nodes.getLength(); i++) { 

     Node node = nodes.item(i); 
     String nodeName = node.getNodeName(); 
     String nodeValue = node.getNodeValue(); 

     System.out.println(nodeName + " = " + nodeValue); 

    } 

} //end of printXpathResult() 

的輸出我得到的代碼

address = null 
buildingnumber = null 
street = null 
city = null 
state = null 
zip = null 

我期待這個輸出

address = null 
buildingnumber = 29 
street = South Lasalle Street 
city = Chicago 
state = Illinois 
zip = 60603 

爲什麼我越來越null雖然buildingnu mber和其他有價值?我怎樣才能得到我想要的輸出?

感謝

編輯 -------------------------------------- ------------------------

public static void printXpathResult(Object result){ 

    NodeList nodes = (NodeList) result; 

    for (int i = 0; i < nodes.getLength(); i++) { 

     Node node = nodes.item(i); 
     String nodeName = node.getNodeName(); 
     String nodeValue = node.getTextContent(); 

     System.out.println(nodeName + " = " + nodeValue); 

    } 

} //end of printXpathResult() 

在此之後我得到下面的輸出

address = 
29 
South Lasalle Street 
Chicago 
Illinois 
60603 

buildingnumber = 29 
street = South Lasalle Street 
city = Chicago 
state = Illinois 
zip = 60603 

爲什麼我獲得地址= 29 ....我認爲應該是address = null

由於

回答

0

在DOM API,getNodeValue()被指定爲總是元素節點返回null(見table at the top of the JavaDoc page for Node)。您可能需要getTextContent()

但是,請注意,對於address元素,getTextContent()不會給你null,而是你會得到所有文本節點後代的連接,包括空白。在實際的使用情況,你可能會使用descendant::而非descendant-or-self::在XPath,所以你不必特別處理的父元素,或者使用類似

descendant-or-self::*[not(*)] 

限制結果葉元素(那些本身沒有任何元素的孩子)。

+0

謝謝。請檢查我的編輯。爲什麼我得到'地址= 29 ....'? – Basit

+0

@Basit我已經添加了一些更多的細節。 –

+0

hhmm謝謝:)。我有另一個問題,但我想我使用另一個帖子。至於這個問題是關心你解釋我真的很好:)謝謝:) – Basit