每天多一点之Dom+Xpath的简单应用

直接看案例:

XML(exercise.xml):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students>
    <student sid="001">
        <name>小明</name>
        <course>
            <java>90</java>
            <oracle>90</oracle>
            <vb>89</vb>
        </course>
    </student>
    <student sid="002">
        <name>小李</name>
        <course>
            <java>9</java>
            <oracle>70</oracle>
            <vb>8</vb>
        </course>
    </student>
    <student sid="003">
        <name>小韩</name>
        <course>
            <java>90</java>
            <oracle>70</oracle>
            <vb>85</vb>
        </course>
    </student>
</students>


TestDomXpath.JAVA:

package com.exercise.domxpath;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class TestDomXpath {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory
                .newDocumentBuilder();
        Document doc = documentBuilder
                .parse("src/com/exercise/domxpath/exercise.xml");

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

        XPathExpression exps = xpath.compile("//students/student");
        NodeList nodeList = (NodeList) exps.evaluate(doc, XPathConstants.NODESET);
        
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(((Element) nodeList.item(i)).getAttribute("sid"));
        }

    }

}
原文地址:https://www.cnblogs.com/hackerd/p/3101484.html