java · 2021-07-05 0

XPath的使用

1.xml

xpath.xml

<location>
    <property>
        <name>city</name>
        <value>beijing</value>
    </property>
    <property>
        <name>district</name>
        <value>chaoyang</value>
    </property>
</location>

2.XPath使用

    @Test
    public void test1() throws Exception {
        String path = this.getClass().getResource("/xpath.xml").getPath();

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);

        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(path);

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

        NodeList nodes = (NodeList) xPath.evaluate("location/property", doc, XPathConstants.NODESET);

        String name = "";
        String value = "";
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            name = (String) xPath.evaluate("name", node, XPathConstants.STRING);
            value = (String) xPath.evaluate("value", node, XPathConstants.STRING);
            System.out.println("name=" + name + ";value=" + value);
        }
    }