首先 关于dom4j的API,有如下:
当然 其中的实体引用有以下:
测试使用环境:
使用Maven搭建web环境,pom.xml文件配置如下:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.it.sxd</groupId> 4 <artifactId>springModel</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 <packaging>war</packaging> 7 <build> 8 <plugins> 9 <plugin> 10 <artifactId>maven-war-plugin</artifactId> 11 <configuration> 12 <version>3.0</version> 13 </configuration> 14 </plugin> 15 </plugins> 16 </build> 17 18 <properties> 19 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 20 <spring.version>4.3.4.RELEASE</spring.version> 21 <hibernate.version>4.3.8.Final</hibernate.version> 22 </properties> 23 24 <dependencies> 25 <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api --> 26 <dependency> 27 <groupId>javax.persistence</groupId> 28 <artifactId>persistence-api</artifactId> 29 <version>1.0</version> 30 </dependency> 31 32 <!-- junit --> 33 <dependency> 34 <groupId>junit</groupId> 35 <artifactId>junit</artifactId> 36 <version>4.12</version> 37 <scope>test</scope> 38 </dependency> 39 40 <!-- spring --> 41 <dependency> 42 <groupId>org.springframework</groupId> 43 <artifactId>spring-core</artifactId> 44 <version>${spring.version}</version> 45 </dependency> 46 47 <dependency> 48 <groupId>org.springframework</groupId> 49 <artifactId>spring-beans</artifactId> 50 <version>${spring.version}</version> 51 </dependency> 52 53 <dependency> 54 <groupId>org.springframework</groupId> 55 <artifactId>spring-context</artifactId> 56 <version>${spring.version}</version> 57 </dependency> 58 59 <dependency> 60 <groupId>org.springframework</groupId> 61 <artifactId>spring-tx</artifactId> 62 <version>${spring.version}</version> 63 </dependency> 64 65 <dependency> 66 <groupId>org.springframework</groupId> 67 <artifactId>spring-web</artifactId> 68 <version>${spring.version}</version> 69 </dependency> 70 71 <dependency> 72 <groupId>org.springframework</groupId> 73 <artifactId>spring-test</artifactId> 74 <version>${spring.version}</version> 75 <scope>test</scope> 76 </dependency> 77 78 <!-- 使用SpringMVC需配置 --> 79 <dependency> 80 <groupId>org.springframework</groupId> 81 <artifactId>spring-webmvc</artifactId> 82 <version>${spring.version}</version> 83 </dependency> 84 <!-- spring cglib 代理 --> 85 <dependency> 86 <groupId>cglib</groupId> 87 <artifactId>cglib</artifactId> 88 <version>2.2.2</version> 89 </dependency> 90 <!-- 关系型数据库整合时需配置 如hibernate jpa等 --> 91 <dependency> 92 <groupId>org.springframework</groupId> 93 <artifactId>spring-orm</artifactId> 94 <version>${spring.version}</version> 95 </dependency> 96 97 <!-- hibernate --> 98 <dependency> 99 <groupId>org.hibernate</groupId> 100 <artifactId>hibernate-core</artifactId> 101 <version>${hibernate.version}</version> 102 </dependency> 103 104 <dependency> 105 <groupId>org.hibernate</groupId> 106 <artifactId>hibernate-ehcache</artifactId> 107 <version>${hibernate.version}</version> 108 </dependency> 109 110 <!-- 二级缓存ehcache --> 111 <dependency> 112 <groupId>net.sf.ehcache</groupId> 113 <artifactId>ehcache</artifactId> 114 <version>2.9.0</version> 115 </dependency> 116 117 <!-- log4j --> 118 <dependency> 119 <groupId>log4j</groupId> 120 <artifactId>log4j</artifactId> 121 <version>1.2.17</version> 122 </dependency> 123 124 <!-- mysql连接 --> 125 <dependency> 126 <groupId>mysql</groupId> 127 <artifactId>mysql-connector-java</artifactId> 128 <version>5.1.34</version> 129 </dependency> 130 131 <!-- c3p0数据源 --> 132 <dependency> 133 <groupId>com.mchange</groupId> 134 <artifactId>c3p0</artifactId> 135 <version>0.9.5-pre10</version> 136 </dependency> 137 138 <!-- json --> 139 140 <!-- 1号 --> 141 <dependency> 142 <groupId>com.fasterxml.jackson.core</groupId> 143 <artifactId>jackson-core</artifactId> 144 <version>2.8.1</version> 145 </dependency> 146 <!-- 2号 --> 147 <dependency> 148 <groupId>com.fasterxml.jackson.core</groupId> 149 <artifactId>jackson-annotations</artifactId> 150 <version>2.8.1</version> 151 </dependency> 152 153 <!-- 3号 --> 154 <dependency> 155 <groupId>com.fasterxml.jackson.core</groupId> 156 <artifactId>jackson-databind</artifactId> 157 <version>2.8.1</version> 158 <exclusions> 159 <exclusion> 160 <artifactId>jackson-core</artifactId> 161 <groupId>com.fasterxml.jackson.core</groupId> 162 </exclusion> 163 <exclusion> 164 <artifactId>jackson-annotations</artifactId> 165 <groupId>com.fasterxml.jackson.core</groupId> 166 </exclusion> 167 </exclusions> 168 </dependency> 169 170 <!-- 4号 --> 171 <dependency> 172 <groupId>com.google.code.gson</groupId> 173 <artifactId>gson</artifactId> 174 <version>2.7</version> 175 </dependency> 176 <!-- 5号 --> 177 <dependency> 178 <groupId>net.sf.json-lib</groupId> 179 <artifactId>json-lib</artifactId> 180 <version>2.4</version> 181 <classifier>jdk15</classifier> 182 </dependency> 183 <!-- 5号json-lib还需要以下依赖包 --> 184 <dependency> 185 <groupId>commons-lang</groupId> 186 <artifactId>commons-lang</artifactId> 187 <version>2.5</version> 188 </dependency> 189 <dependency> 190 <groupId>commons-beanutils</groupId> 191 <artifactId>commons-beanutils</artifactId> 192 <version>1.9.2</version> 193 </dependency> 194 <dependency> 195 <groupId>commons-collections</groupId> 196 <artifactId>commons-collections</artifactId> 197 <version>3.2.1</version> 198 </dependency> 199 <dependency> 200 <groupId>commons-logging</groupId> 201 <artifactId>commons-logging</artifactId> 202 <version>1.2</version> 203 </dependency> 204 205 <!-- aop --> 206 <dependency> 207 <groupId>org.aspectj</groupId> 208 <artifactId>aspectjweaver</artifactId> 209 <version>1.8.4</version> 210 </dependency> 211 212 <!-- servlet --> 213 <dependency> 214 <groupId>javax.servlet</groupId> 215 <artifactId>servlet-api</artifactId> 216 <version>3.0-alpha-1</version> 217 <scope>provided</scope> 218 </dependency> 219 220 <dependency> 221 <groupId>javax.servlet</groupId> 222 <artifactId>jstl</artifactId> 223 <version>1.2</version> 224 </dependency> 225 <!-- guava 集合的交并操作 --> 226 <dependency> 227 <groupId>com.google.guava</groupId> 228 <artifactId>guava</artifactId> 229 <version>19.0</version> 230 </dependency> 231 <dependency> 232 <groupId>com.google.guava</groupId> 233 <artifactId>guava-collections</artifactId> 234 <version>r03</version> 235 </dependency> 236 237 <!-- 文件上传 --> 238 <dependency> 239 <groupId>commons-fileupload</groupId> 240 <artifactId>commons-fileupload</artifactId> 241 <version>1.3.1</version> 242 </dependency> 243 <!-- https://mvnrepository.com/artifact/jaxen/jaxen --> 244 <dependency> 245 <groupId>jaxen</groupId> 246 <artifactId>jaxen</artifactId> 247 <version>1.1.6</version> 248 </dependency> 249 250 251 252 253 254 </dependencies> 255 </project>
关于dom4j测试xml文件----实现的代码:
1 package com.sxd.dom4j.test; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 import java.nio.file.Files; 8 import java.util.List; 9 10 import org.dom4j.Attribute; 11 import org.dom4j.Document; 12 import org.dom4j.DocumentException; 13 import org.dom4j.DocumentHelper; 14 import org.dom4j.Element; 15 import org.dom4j.io.OutputFormat; 16 import org.dom4j.io.SAXReader; 17 import org.dom4j.io.XMLWriter; 18 import org.junit.Test; 19 20 public class Dom4jTest { 21 22 @Test 23 public void mainTest() throws IOException, DocumentException{ 24 25 // createXML();//创建XML文件 26 // queryXMLByXPath();//查找XML文件 27 // queryXMLByDom4j();//查找XML文件 28 // queryXMLByReadXML();//查找XML文件 29 updateOdeleteXML();//修改或删除元素 30 } 31 /** 32 * 创建 XML文件 33 * @throws IOException 34 */ 35 public void createXML() throws IOException{ 36 OutputStream out = new FileOutputStream(new File("d:/testXMLFile.xml")); 37 //XMLWriter生成物理文件 38 //但是一般生成的xml文件内容比较紧凑 39 //调用OutputFormat.createPrettyPrint()或者OutputFormat.createCompactFormat()方法可以使XML文件内容格式化输出 40 XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint()); 41 42 //Document定义了XML 文档 43 Document document = DocumentHelper.createDocument(); 44 45 //设置根节点 46 Element elementRoot = document.addElement("根节点"); 47 document.setRootElement(elementRoot); 48 /** 49 * Element和Node的区别在于: 50 * 1.Element代表一个对象,对象中有属性,属性有属性值,对象有文本 51 * 例如:<bean id="myTestBean" class="com.sxd.spring.test1.MyTestBean">测试bean</bean> 52 * 就是一个完整的Element 53 * 2.Node代表任意一个节点,可以是上面的Element,也可以是Element中的某个属性 54 * 例如:id="myTestBean"可以是一个Node 55 * <bean id="myTestBean" class="com.sxd.spring.test1.MyTestBean">测试bean</bean> 也可以是一个Node 56 */ 57 58 Element element1 = elementRoot.addElement("一层节点"); 59 element1.addAttribute("属性名1","属性值1"); 60 61 Element element2_1 = element1.addElement("二层节点"); 62 element2_1.addAttribute("id", "attr2_1").addAttribute("name", "attr2_1"); 63 Element element2_2 = element1.addElement("二层节点"); 64 element2_2.addAttribute("id", "attr2_2").addAttribute("name", "attr2_2"); 65 Element element2_3 = element1.addElement("二层节点"); 66 element2_3.addAttribute("id", "attr2_3").addAttribute("name", "attr2_3"); 67 /** 68 * <beans>text</beans> 69 */ 70 element2_2.addText("开始节点和结束节点之间的文本文字"); 71 /** 72 * 术语 CDATA 指的是不应由 XML 解析器进行解析的文本数据(Unparsed Character Data)。 73 */ 74 element2_3.addCDATA("CDATA中的文本 是xml不应该解析的文本数据,一般放置为包含<或者&这种特殊字符的文本"); 75 76 writer.write(document); 77 writer.close(); 78 } 79 80 81 82 /** 83 * 查看 XML文件 使用SAXReader----使用了xpath解析 84 * @throws DocumentException 85 */ 86 public void queryXMLByXPath() throws DocumentException{ 87 SAXReader reader = new SAXReader(); 88 Document document = reader.read(new File("d:/testXMLFile.xml")); 89 //使用XPath语法 selectNodes()方法得到所有的Element 这里需要Jaxen是一个开源的XPath库 90 List<Element> list = document.selectNodes("根节点|一层节点|二层节点"); 91 if(!list.isEmpty() && list!=null && list.size()>0){ 92 for (Element element : list) { 93 just4Element(element); 94 } 95 } 96 } 97 98 /** 99 * 递归 抽离element 100 * @param element 101 */ 102 public void just4Element(Element element){ 103 justPlayElement(element); 104 List<Element> list = element.elements(); 105 if(!list.isEmpty() && list.size()>0 && list!=null){ 106 for (Element e : list) { 107 just4Element(e); 108 } 109 } 110 } 111 112 113 /** 114 * 重载 展示element信息 默认展示属性信息 115 * @param element 116 */ 117 public void justPlayElement(Element element){ 118 boolean showSon = true; 119 justPlayElement(element,showSon); 120 } 121 122 /** 123 * 展示element信息 124 * @param element 125 */ 126 public void justPlayElement(Element element,boolean showSon){ 127 System.out.println("节点名称:"+element.getName()); 128 System.out.println("节点文本:"+element.getText()); 129 int attributeSum = element.attributeCount(); 130 System.out.println("节点属性个数:"+attributeSum); 131 //或者 132 if(showSon){ 133 List<Attribute> attList = element.attributes(); 134 if(attList!= null && attList.size()>0){ 135 for (Attribute attribute : attList) { 136 System.out.println("节点"+element.getName()+"的属性->"+attribute.getName()+":"+attribute.getValue()); 137 } 138 } 139 } 140 141 System.out.println("----------------------------------------------------------------------------------------"); 142 143 } 144 145 146 /** 147 * 查看 XML文件 使用SAXReader --纯dom4j解析 148 * @throws DocumentException 149 */ 150 public void queryXMLByDom4j() throws DocumentException{ 151 SAXReader reader = new SAXReader(); 152 Document document = reader.read(new File("d:/testXMLFile.xml")); 153 //先得到根节点 154 Element element = document.getRootElement(); 155 if(element!= null){//然后调用递归 去取出 根节点中所有结点信息 156 just4Element(element); 157 } 158 } 159 160 /** 161 * 查看 XML文件 通过读取XML字符串的方式 162 * @throws IOException 163 * @throws DocumentException 164 */ 165 public void queryXMLByReadXML() throws IOException, DocumentException{ 166 File file = new File("d:/testXMLFile.xml"); 167 List<String> list = Files.readAllLines(file.toPath()); 168 StringBuilder xmlStr = new StringBuilder();//优先使用StringBuilder[单线程 速度更快] 169 for (String string : list) { 170 xmlStr.append(string); 171 } 172 //将字符串转化为XML 173 Document document = DocumentHelper.parseText(xmlStr.toString()); 174 //先得到根节点 175 Element element = document.getRootElement(); 176 if(element!= null){//然后调用递归 去取出 根节点中所有结点信息 177 just4Element(element); 178 } 179 } 180 181 /** 182 * 修改XML文件内容 183 * @throws DocumentException 184 * @throws IOException 185 */ 186 public void updateOdeleteXML() throws DocumentException, IOException{ 187 SAXReader reader = new SAXReader(); 188 Document document = reader.read(new File("d:/testXMLFile.xml")); 189 Element elementRoot = document.getRootElement(); 190 Element element = (Element) elementRoot.selectSingleNode("一层节点"); 191 justPlayElement(element,true);//调用 展示标签信息 不展示子层信息 192 193 194 element.addAttribute("属性名2", "属性值2"); 195 element.addText("一层节点的文本 是修改之后的结果"); 196 element.setAttributeValue("属性名1", "修改之后的属性值1");//Deprecated. As of version 0.5. Please use addAttribute(QName, String) instead. WILL BE REMOVED IN dom4j-1.6 !! 197 element.addAttribute("属性名1", "二次修改之后的属性值1"); 198 199 justPlayElement(element);//展示 修改之后的 元素信息 200 201 List<Element> elements = element.elements(); 202 for (Element element2 : elements) { 203 if(element2.attributeValue("id").equals("attr2_1")){ 204 element2.getParent().remove(element2); 205 } 206 } 207 208 OutputStream outputStream = new FileOutputStream("d:/testXMLFile.xml"); 209 XMLWriter writer = new XMLWriter(outputStream, OutputFormat.createPrettyPrint()); 210 writer.write(document); 211 writer.close(); 212 213 } 214 215 216 217 218 219 220 }
查询所有的展示结果:
在测试过程中有如下的错误:
错误1:
1 错误1: 2 org.dom4j.IllegalAddException: The node "org.dom4j.tree.DefaultElement@2e5c649 [Element: <一层节点 attributes: []/>]" could not be added to the branch "null" because: Cannot add another element to this Document as it already has a root element of: 根节点 3 at org.dom4j.tree.AbstractDocument.checkAddElementAllowed(AbstractDocument.java:241) 4 at org.dom4j.tree.AbstractDocument.add(AbstractDocument.java:203) 5 at org.dom4j.tree.AbstractDocument.addElement(AbstractDocument.java:173) 6 at com.sxd.dom4j.test.Dom4jTest.createXML(Dom4jTest.java:52) 7 at com.sxd.dom4j.test.Dom4jTest.mainTest(Dom4jTest.java:23) 8 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 9 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 10 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 11 at java.lang.reflect.Method.invoke(Unknown Source) 12 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) 13 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 14 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) 15 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 16 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) 17 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) 18 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) 19 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) 20 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) 21 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) 22 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) 23 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) 24 at org.junit.runners.ParentRunner.run(ParentRunner.java:363) 25 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) 26 at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 27 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) 28 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) 29 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) 30 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
解决方法:
错误2:
1 报错2: 2 java.lang.NoClassDefFoundError: org/jaxen/NamespaceContext 3 at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230) 4 at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207) 5 at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164) 6 at com.sxd.dom4j.test.Dom4jTest.queryXMLBySAXReader(Dom4jTest.java:87) 7 at com.sxd.dom4j.test.Dom4jTest.mainTest(Dom4jTest.java:27) 8 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 9 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 10 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 11 at java.lang.reflect.Method.invoke(Unknown Source) 12 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) 13 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 14 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) 15 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 16 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) 17 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) 18 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) 19 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) 20 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) 21 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) 22 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) 23 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) 24 at org.junit.runners.ParentRunner.run(ParentRunner.java:363) 25 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) 26 at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 27 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) 28 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) 29 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) 30 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) 31 Caused by: java.lang.ClassNotFoundException: org.jaxen.NamespaceContext 32 at java.net.URLClassLoader.findClass(Unknown Source) 33 at java.lang.ClassLoader.loadClass(Unknown Source) 34 at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) 35 at java.lang.ClassLoader.loadClass(Unknown Source) 36 ... 28 more
解决方法:
Maven路径:
1 <!-- https://mvnrepository.com/artifact/jaxen/jaxen --> 2 <dependency> 3 <groupId>jaxen</groupId> 4 <artifactId>jaxen</artifactId> 5 <version>1.1.6</version> 6 </dependency>