30 expression = "//project[name=\"Telecommunication Project\"]/name";
31 System.out.println(reader.read(expression, XPathConstants.STRING));
32 //获取projects的第三个名字为project的子节点的全部
33 expression = "/projects/project[3]";
34 NodeList thirdProject = (NodeList) reader.read(expression, XPathConstants.NODESET);
35 traverse(thirdProject);
36 }
37
38 private static void traverse(NodeList rootNode) {
39 for (int index = 0; index < rootNode.getLength(); index++) {
40 Node aNode = rootNode.item(index);
41 if (aNode.getNodeType() == Node.ELEMENT_NODE) {
42 NodeList childNodes = aNode.getChildNodes();
43 if (childNodes.getLength() > 0) {
44 System.out.println("Name:" + aNode.getNodeName() + ",Value:"
45 + aNode.getTextContent());
46 }
47 traverse(aNode.getChildNodes());
48 }
49 }
50 }
51 }
52
53 class XPathReader {
54 private String xmlFile;
55 private Document xmlDocument;
56 private XPath xPath;
57 public XPathReader(String xmlFile) {
58 this.xmlFile = xmlFile;
59 initObjects();
60 }
61 private void initObjects() {
62 try {
63 //先将XML文件解析为DOM模型,并存储在内存中。
64 xmlDocument = DocumentBuilderFactory.newInstance()
65 .newDocumentBuilder().parse(xmlFile);
66 //实例化XPath对象
67 xPath = XPathFactory.newInstance().newXPath();
68 } catch (IOException ex) {
69 } catch (SAXException ex) {
70 } catch (ParserConfigurationException ex) {
71 }
72 }
73 public Object read(String expression, QName returnType) {
74 try {
75 //如果该表达式会被反复执行,那么先将其编译之后再执行可以提高效率。
76 XPathExpression xPathExpression = xPath.compile(expression);
77 //returnType表示eva luate将返回的节点类型。
78 return xPathExpression.eva luate(xmlDocument, returnType);
79 } catch (XPathExpressionException ex) {
80 return null;
81 }
82 }
83 }
4. 构造XML的DOM模型,同时输出该DOMTreeModel到XML文件。
1 public class MyTest {
2 public static void main(String[] args) {
3 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
4 Element root = null, attr = null,subAttr = null;
5 try {
6 factory.setIgnoringElementContentWhitespace(true);
7 DocumentBuilder db = factory.newDocumentBuilder();
8 Document xmldoc = db.parse(new File("D:/Test.xml"));
9 root = xmldoc.getDocumentElement();
10 //1. 给原有DOMTreeModel添加新节点
11 //创建子Element
12 attr = xmldoc.createElement("attribute4");
13 subAttr = xmldoc.createElement("subAttribute");
14 //给Element设置文本数据
15 subAttr.setTextContent("Hello, I am sub-