在 java 代码中使用 xpath 时出错

error on using xpath in java code

我正在尝试获取 xpath 表达式的结果,我的 xml 文件是这样的:

<?xml version="1.0"?>
<all>
<test1>
</test1>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
</catalog>
</all>

我的 java 代码是:

public class xpath_test {

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


        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = (Document) builder.parse("C:\Users\HC\Desktop\dataset\book.xml");
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("/all/catalog");
        NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
        }

    }
}

我遇到了一个例外:

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl cannot be cast to org.jdom2.Document

特别是这一行Document doc = (Document) builder.parse("C:\Users\HC\Desktop\dataset\book.xml");

知道我导入 import org.jdom2.Document;

尽量使用标准界面

import org.w3c.dom.document

而不是

import org.jdom2.Document