2013-07-12 73 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