XPath Java使用双斜杠计算表达式,对应指定了命名空间的文档

时间:2017-03-24 16:17:48

标签: java xml xpath namespaces

这是一些Java代码:

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XpathQuestion {
public static void main(String[] args) throws SAXException, IOException, XPathExpressionException, ParserConfigurationException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);

    DocumentBuilder documentBuilder = factory.newDocumentBuilder();

    XPath xpath = XPathFactory.newInstance().newXPath();

    File xmlFile = new File("stackoverflow.xml");

    Document doc = documentBuilder.parse(new InputSource(xmlFile.getAbsolutePath()));

    NodeList nodes1 = (NodeList) (xpath.evaluate("//AB", doc,
            XPathConstants.NODESET));

    NodeList nodes2 = (NodeList) (xpath.evaluate("//AB/stat", doc,
            XPathConstants.NODESET));

    int nodes1Length = nodes1.getLength();
    int nodes2Length = nodes2.getLength();

    System.out.println(nodes1Length);
    System.out.println(nodes2Length);

}
}

上面代码中的文档stackoverflow.xml如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<ns:document xmlns:ns="http://www.noinfohere.de">
  <ns:env>
    <ns:trans>
      <ns:version>123</ns:version>
    </ns:trans>
    <ns:sender>
        <ns:senderId>abc</ns:senderId>
    </ns:sender>
  </ns:env>
      <ns:AB>
           <ns:stat>asdf</ns:stat>
      </ns:AB>
</ns:document>

当我运行程序时,输出为:

0
1

表示:nodes1Length = 0和 nodes2Length = 1

我不明白的是:为什么nodes1Length = 0? xpath表达式“// AB”应该找到文档中的所有AB元素。我的计划有什么问题?

Thanx 4你的帮助。

0 个答案:

没有答案