1. Java项目(Eclipse)结构
2. 项目下载(0积分)
dom4j_xpath_junitTest.zip
3. 代码
package org.foo.utils; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.junit.Test; final public class XmlUtils { private static URL URL = XmlUtils.class.getClassLoader().getResource("configuration.xml"); /** ---------------------------------- *\ 获取Document对象 \* ---------------------------------- */ public static Document getDocument(URL url) throws DocumentException { // url = XmlUtils.class.getResource("configuration.xml"); SAXReader reader = new SAXReader(); return reader.read( url ); } public static Document getDocument(String xmlString) throws DocumentException { /* xmlString = "<configuration> " + " <users> " + " <user id='user_1' loginName='zhangsan' password='123'/> " + " <user id='user_2' loginName='lisi' password='456'> " + " <role name='admin'/> " + " <role name='programmer'/> " + " </user> " + " </users> " + "</configuration> " ; */ return DocumentHelper.parseText(xmlString); } public static Document getDocument() throws DocumentException { // 空文档 return DocumentHelper.createDocument(); } /** ---------------------------------- *\ 将文档写入XML文件 \* ---------------------------------- */ // 普通写入(全英文,无缩进无换行) public static void write2Xml(Document document) throws IOException { XMLWriter writer = null; try { writer = new XMLWriter( new FileWriter(URL.getPath()) ); writer.write(document); } finally { if (writer != null) { writer.close(); } } } // 格式化写入(指定编码,缩进+换行) public static void write2XmlWithPrettyFormatAndEncoding(Document document, String encoding) throws IOException { XMLWriter writer = null; try { // format OutputFormat format = OutputFormat.createPrettyPrint(); // characterSet, eg. UTF-8 GBK format.setEncoding(encoding); writer = new XMLWriter( new FileWriter(URL.getPath()), format ); writer.write(document); } finally { if (writer != null) { writer.close(); } } } /** ---------------------------------- *\ 字符串 <==> XML \* ---------------------------------- */ public static Document xmlString2Document(String xmlString) throws DocumentException { if (xmlString == null) { xmlString = "<configuration> " + " <users> " + " <user id='user_1' loginName='zhangsan' password='123'/> " + " <user id='user_2' loginName='lisi' password='456'> " + " <role name='admin'/> " + " <role name='programmer'/> " + " </user> " + " </users> " + "</configuration> " ; } return DocumentHelper.parseText(xmlString); } public static String document2XmlString(Document document) { return document.asXML(); } /** ---------------------------------- *\ 节点对象操作 \* ---------------------------------- */ // 1. 获取根节点 @Test public void testOperationNode_1() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); System.out.println("<" + rootElement.getName() + ">"); } // 2. 获取节点的<第一个>子节点 @Test public void testOperationNode_2() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); Element firstChild = rootElement.element("users"); System.out.println("<" + firstChild.getName() + ">"); } // 3. 获取标签体内容( Text,CDATA and Entitynodes ) @Test public void testOperationNode_3() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); String text = rootElement.getText(); System.out.println("[" + text + "]"); } // 4. 获取<所有的>子节点 @Test public void testOperationNode_4() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); Element firstChild = rootElement.element("users"); List<Element> children = firstChild.elements(); for (Iterator it = children.iterator(); it.hasNext();) { Element e = (Element) it.next(); System.out.println( "<" + e.getName() + ">"); } } // 5. 遍历<子节点> @Test public void testOperationNode_5() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); Element firstChild = rootElement.element("users"); for (Iterator it = firstChild.elementIterator(); it.hasNext();) { Element e = (Element) it.next(); System.out.println( "<" + e.getName() + ">"); } } // 6. 遍历<指定名称>的<子节点> @Test public void testOperationNode_6() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); for (Iterator it = rootElement.elementIterator("users"); it.hasNext();) { Element e = (Element) it.next(); System.out.println( "<" + e.getName() + ">"); } } // 7. 添加<子节点> 注:操作节点后,需要将 document写入xml文件 @Test public void testOperationNode_7() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); rootElement.addElement("addElment"); System.out.println( document2XmlString(document) ); } // 8. 给节点<添加文本> @Test public void testOperationNode_8() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); rootElement.addElement("addElment") .setText("a new child");; System.out.println( document2XmlString(document) ); } // 9. 删除<子节点> @Test public void testOperationNode_9() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); rootElement.remove( rootElement.element("users") ); System.out.println( document2XmlString(document) ); } // 10. 添加 CDATA节点 @Test public void testOperationNode_10() throws Exception { Document document = getDocument( URL ); Element rootElement = document.getRootElement(); rootElement.addCDATA("<c:if test=\"{wahh}\"></c:if>"); System.out.println( document2XmlString(document) ); } // 11. 根据<ID属性值>获取节点 @Test public void testOperationNode_11() throws Exception { Document document = getDocument( URL ); // ID="user_1" Element element = document.elementByID("user_1"); System.out.println( element.getName() ); } /** ---------------------------------- *\ 节点对象的属性操作 \* ---------------------------------- */ // 1. 获取某节点的<属性节点> @Test public void testOperationAttr_1() throws Exception { Document document = getDocument( URL ); Element element = document.elementByID("user_1"); Attribute loginNameAttribute = element.attribute("loginName"); System.out.println(loginNameAttribute); } // 2. 获取<属性节点>的值 @Test public void testOperationAttr_2() throws Exception { Document document = getDocument( URL ); Element element = document.elementByID("user_1"); Attribute loginNameAttribute = element.attribute("loginName"); System.out.println(loginNameAttribute.getValue()); System.out.println(loginNameAttribute.getText()); } // 3. 删除<属性节点> @Test public void testOperationAttr_3() throws Exception { Document document = getDocument( URL ); Element element = document.elementByID("user_1"); Attribute loginNameAttribute = element.attribute("loginName"); element.remove(loginNameAttribute); System.out.println( document2XmlString(document) ); } // 4. 遍历节点的所有属性 @Test public void testOperationAttr_4() throws Exception { Document document = getDocument( URL ); Element element = document.elementByID("user_1"); for (Iterator it = element.attributeIterator(); it.hasNext();){ Attribute attribute = (Attribute) it.next(); String attributeName = attribute.getName(); String attributeValue = attribute.getValue(); System.out.println(attributeName + "=" + attributeValue); } } // 5. <添加/替换>属性节点 @Test public void testOperationAttr_5() throws Exception { Document document = getDocument( URL ); Element element = document.elementByID("user_1"); element.addAttribute("loginName", "zhang123"); // 替换 element.addAttribute("newAttr", "wahh"); // 添加 System.out.println(document2XmlString(document)); } /** ---------------------------------- *\ xpath-路径表达式 \* ---------------------------------- */ /* / 从根节点选取; 从子节点中选 // 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置; 从后代中选 . 选取当前节点 .. 选取当前节点的父节点 @ 选取属性 */ // 1. "/configuration/users/user" 从根节点开始,选取所有的<user> @Test public void testXpath_1() throws Exception { Document document = getDocument( URL ); String xpathExpression = "/configuration/users/user"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } // 2. "//user" 选取所有的<user> @Test public void testXpath_2() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//user"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } // 3. "//users/user" 选取<users>的所有<user>子节点 @Test public void testXpath_3() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//users/user"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } // 4. "/configuration//user" 选取<configuration>的所有<user>后代节点 @Test public void testXpath_4() throws Exception { Document document = getDocument( URL ); String xpathExpression = "/configuration//user"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } // 5. "//@loginName" 选取有属性名为 loginName 的属性节点 @Test public void testXpath_5() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//@loginName"; List<Attribute> attributeList = document.selectNodes(xpathExpression); for (Attribute attribute : attributeList) { System.out.println(attribute.getValue()); } } // 6. "//@password='123'" 是否存在 loginName='zhangsan' 的节点 @Test public void testXpath_6() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//@password='123'"; List<Boolean> list = document.selectNodes(xpathExpression); for (Boolean isExist : list) { System.out.println(isExist); } } /** ---------------------------------- *\ xpath-谓语(Predicates) 谓语用来查找某个特定的节点或者包含某个指定的值的节点。 谓语被嵌在方括号中。 \* ---------------------------------- */ // 1. "//user[1]" 选取第一个<user>节点, 节点索引从1开始 @Test public void testPredicates_1() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//user[1]"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } // 2. "//user[last()]" 选取最后<user>节点 @Test public void testPredicates_2() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//user[last()]"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } // 3. "//user[last()-1]" 选倒数第二个<user>节点 @Test public void testPredicates_3() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//user[last()-1]"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } // 4. "//user[position()<3]" 选前两个<user>节点 @Test public void testPredicates_4() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//user[position()<3]"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } // 5. "//user[@loginName]" 选有loginName属性的<user>节点 @Test public void testPredicates_5() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//user[@loginName]"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } // 6. "//user[@loginName='zhangsan']" 选 loginName属性=zhangsan 的<user>节点 @Test public void testPredicates_6() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//user[@loginName='zhangsan']"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("ID")); } } /** ---------------------------------- *\ 通配符 \* ---------------------------------- */ /* * 匹配任何元素节点 @* 匹配任何属性节点 node() 匹配任何类型节点 */ // 1. "//products/*" products的所有子节点(元素节点) @Test public void testWildcard_1() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//products/*"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.attributeValue("name")); } } // 2. "//*" 所有元素节点 @Test public void testWildcard_2() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//*"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.getName()); } } // 3. "//product[@*]" 带有属性的<product>节点 @Test public void testWildcard_3() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//product[@*]"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { System.out.println(element.getName()); } } // 4. "//products/node()" <products>所有节点(元素节点,文本节点) @Test public void testWildcard_4() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//products/node()"; List<Node> nodeList = document.selectNodes(xpathExpression); for (Node node : nodeList) { short nodeType = node.getNodeType(); switch (nodeType) { case Node.ELEMENT_NODE: System.out.println("<" + node.getName() + ">"); break; case Node.ATTRIBUTE_NODE: System.out.println(node.getName() + "=" + node.getText()); break; case Node.TEXT_NODE: System.out.println("[" + node.getText() + "]"); break; } } } /** ---------------------------------- *\ | 路径 连接, 求多个路径的并集 \* ---------------------------------- */ @Test public void testPathUnion() throws Exception { Document document = getDocument( URL ); String xpathExpression = "//product[@name='Java'] | //user[@ID='user_3']"; List<Element> nodeList = document.selectNodes(xpathExpression); for (Element element : nodeList) { String nodeName = element.getName(); System.out.print("<" + nodeName); for (Object attr : element.attributes()) { Attribute attribute = (Attribute) attr; String attributeName = attribute.getName(); String attributeValue = attribute.getValue(); System.out.print(" " + attributeName + "=\"" + attributeValue + "\""); } System.out.println(">"); } } }
<?xml version="1.0" encoding="UTF-8"?> <configuration> <users> <user ID="user_1" loginName="zhangsan" password="123"/> <user ID="user_2" loginName="lisi" password="123"> <role name="admin"/> <role name="programmer"/> </user> <user ID="user_3" loginName="zhangsan" password="123"/> </users> <products> <product name="Java" price="99.99"/> <product name="JavaScript" price="77.99"/> <product name="C" price="66.99"/> <product name="C++" price="55.99"/> <product name="C#" price="44.99"/> <product/> </products> </configuration>