forked from wujun728/jun_java_plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestXPath.java
More file actions
57 lines (49 loc) · 1.8 KB
/
TestXPath.java
File metadata and controls
57 lines (49 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* 普通DOM与XPath
* @author licheng
*
*/
public class TestXPath {
public static void main(String[] args) {
read();
}
public static void read() {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
InputStream in = TestXPath.class.getClassLoader().getResourceAsStream("university.xml");
Document doc = builder.parse(in);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
// 选取所有class元素的name属性
// XPath语法介绍: http://w3school.com.cn/xpath/
XPathExpression expr = xpath.compile("//class/@name");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println("name = " + nodes.item(i).getNodeValue());
}
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}