3

当我运行以下代码时,我得到输出Left:而不是Left: 16.

    // Retrieve DOM from XML file
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    Document dom = null;
    try {
        db = dbf.newDocumentBuilder();
        dom = db.parse("config");
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();

    try {
        String left = (String) xPath.evaluate(
                "/settings/boundaries[0]/left[0]", dom,
                XPathConstants.STRING);
        System.out.println("Left: " + left);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

这是XML文件

<settings>
    <boundaries>
        <left>16</left>
        <right>301</right>
        <bottom>370</bottom>
        <top>171</top>
    </boundaries>
</settings>

编辑:根据答案,这应该有效,但它没有:

// Retrieve DOM from XML file
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    Document dom = null;
    try {
        db = dbf.newDocumentBuilder();
        dom = db.parse("config");
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();

    try {
        String left = (String) xPath.evaluate(
                "/settings/boundaries[0]/left[0]/text()", dom,
                XPathConstants.STRING);
        System.out.println("Left: " + left);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

另请注意,此代码,

Element el = (Element) dom.getDocumentElement()
            .getElementsByTagName("boundaries").item(0);

System.out.println(el.getElementsByTagName("left").item(0));

印刷[left: null]

4

3 回答 3

4

节点从 1 开始索引。尝试/settings/boundaries[1]/left[1]

于 2012-05-04T23:14:15.830 回答
2

您正在使用节点的 toString() 定义。这没有记录在案,特别是做任何事情。如果您希望节点名称使用 XPathConstants.NODE 并使用节点 API,或者如果您希望在评估调用中将值附加 .text() 到您的 xpath 字符串。

于 2012-05-04T21:06:03.093 回答
2

正如我所使用的那样,您必须在末尾添加 /text() 以检索该节点上的数据

/settings/boundaries[0]/left[0]/text()

于 2012-05-04T22:39:36.487 回答