在java代码

时间:2016-03-13 19:23:38

标签: java xml xpath jdom jdom-2

我正在尝试获取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;

1 个答案:

答案 0 :(得分:1)

尝试使用标准界面

import org.w3c.dom.document

而不是

import org.jdom2.Document