0

我正在使用 xPath 来获取节点值。这是我的xml

<?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

为什么虽然 buildingnumber 和 other 有值但我得到 null ?我怎样才能得到我想要的输出?

谢谢

编辑 - - - - - - - - - - - - - - - - - - - - - - - - - -------------

 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

谢谢

4

1 回答 1

0

在 DOM API 中,getNodeValue()指定为始终返回null元素节点(请参阅JavaDoc 页面顶部的表格Node)。你可能想要getTextContent()

但是,请注意,对于address元素,getTextContent()不会给您 null,而是您将获得所有文本节点后代的串联,包括空格。在实际用例中,您可能会使用descendant::而不是descendant-or-self::在 xpath 中,因此您不必专门处理父元素,或者使用类似的东西

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

将结果限制为叶元素(那些本身没有任何子元素的元素)。

于 2013-07-12T09:11:38.113 回答