首先 关于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.0modelVersion> 3 <groupId>com.it.sxdgroupId> 4 <artifactId>springModelartifactId> 5 <version>0.0.1-SNAPSHOTversion> 6 <packaging>warpackaging> 7 <build> 8 <plugins> 9 <plugin> 10 <artifactId>maven-war-pluginartifactId> 11 <configuration> 12 <version>3.0version> 13 configuration> 14 plugin> 15 plugins> 16 build> 17 18 <properties> 19 <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> 20 <spring.version>4.3.4.RELEASEspring.version> 21 <hibernate.version>4.3.8.Finalhibernate.version> 22 properties> 23 24 <dependencies> 25 26 <dependency> 27 <groupId>javax.persistencegroupId> 28 <artifactId>persistence-apiartifactId> 29 <version>1.0version> 30 dependency> 31 32 33 <dependency> 34 <groupId>junitgroupId> 35 <artifactId>junitartifactId> 36 <version>4.12version> 37 <scope>testscope> 38 dependency> 39 40 41 <dependency> 42 <groupId>org.springframeworkgroupId> 43 <artifactId>spring-coreartifactId> 44 <version>${spring.version}version> 45 dependency> 46 47 <dependency> 48 <groupId>org.springframeworkgroupId> 49 <artifactId>spring-beansartifactId> 50 <version>${spring.version}version> 51 dependency> 52 53 <dependency> 54 <groupId>org.springframeworkgroupId> 55 <artifactId>spring-contextartifactId> 56 <version>${spring.version}version> 57 dependency> 58 59 <dependency> 60 <groupId>org.springframeworkgroupId> 61 <artifactId>spring-txartifactId> 62 <version>${spring.version}version> 63 dependency> 64 65 <dependency> 66 <groupId>org.springframeworkgroupId> 67 <artifactId>spring-webartifactId> 68 <version>${spring.version}version> 69 dependency> 70 71 <dependency> 72 <groupId>org.springframeworkgroupId> 73 <artifactId>spring-testartifactId> 74 <version>${spring.version}version> 75 <scope>testscope> 76 dependency> 77 78 79 <dependency> 80 <groupId>org.springframeworkgroupId> 81 <artifactId>spring-webmvcartifactId> 82 <version>${spring.version}version> 83 dependency> 84 85 <dependency> 86 <groupId>cglibgroupId> 87 <artifactId>cglibartifactId> 88 <version>2.2.2version> 89 dependency> 90 91 <dependency> 92 <groupId>org.springframeworkgroupId> 93 <artifactId>spring-ormartifactId> 94 <version>${spring.version}version> 95 dependency> 96 97 98 <dependency> 99 <groupId>org.hibernategroupId> 100 <artifactId>hibernate-coreartifactId> 101 <version>${hibernate.version}version> 102 dependency> 103 104 <dependency> 105 <groupId>org.hibernategroupId> 106 <artifactId>hibernate-ehcacheartifactId> 107 <version>${hibernate.version}version> 108 dependency> 109 110 111 <dependency> 112 <groupId>net.sf.ehcachegroupId> 113 <artifactId>ehcacheartifactId> 114 <version>2.9.0version> 115 dependency> 116 117 118 <dependency> 119 <groupId>log4jgroupId> 120 <artifactId>log4jartifactId> 121 <version>1.2.17version> 122 dependency> 123 124 125 <dependency> 126 <groupId>mysqlgroupId> 127 <artifactId>mysql-connector-javaartifactId> 128 <version>5.1.34version> 129 dependency> 130 131 132 <dependency> 133 <groupId>com.mchangegroupId> 134 <artifactId>c3p0artifactId> 135 <version>0.9.5-pre10version> 136 dependency> 137 138 139 140 141 <dependency> 142 <groupId>com.fasterxml.jackson.coregroupId> 143 <artifactId>jackson-coreartifactId> 144 <version>2.8.1version> 145 dependency> 146 147 <dependency> 148 <groupId>com.fasterxml.jackson.coregroupId> 149 <artifactId>jackson-annotationsartifactId> 150 <version>2.8.1version> 151 dependency> 152 153 154 <dependency> 155 <groupId>com.fasterxml.jackson.coregroupId> 156 <artifactId>jackson-databindartifactId> 157 <version>2.8.1version> 158 <exclusions> 159 <exclusion> 160 <artifactId>jackson-coreartifactId> 161 <groupId>com.fasterxml.jackson.coregroupId> 162 exclusion> 163 <exclusion> 164 <artifactId>jackson-annotationsartifactId> 165 <groupId>com.fasterxml.jackson.coregroupId> 166 exclusion> 167 exclusions> 168 dependency> 169 170 171 <dependency> 172 <groupId>com.google.code.gsongroupId> 173 <artifactId>gsonartifactId> 174 <version>2.7version> 175 dependency> 176 177 <dependency> 178 <groupId>net.sf.json-libgroupId> 179 <artifactId>json-libartifactId> 180 <version>2.4version> 181 <classifier>jdk15classifier> 182 dependency> 183 184 <dependency> 185 <groupId>commons-langgroupId> 186 <artifactId>commons-langartifactId> 187 <version>2.5version> 188 dependency> 189 <dependency> 190 <groupId>commons-beanutilsgroupId> 191 <artifactId>commons-beanutilsartifactId> 192 <version>1.9.2version> 193 dependency> 194 <dependency> 195 <groupId>commons-collectionsgroupId> 196 <artifactId>commons-collectionsartifactId> 197 <version>3.2.1version> 198 dependency> 199 <dependency> 200 <groupId>commons-logginggroupId> 201 <artifactId>commons-loggingartifactId> 202 <version>1.2version> 203 dependency> 204 205 206 <dependency> 207 <groupId>org.aspectjgroupId> 208 <artifactId>aspectjweaverartifactId> 209 <version>1.8.4version> 210 dependency> 211 212 213 <dependency> 214 <groupId>javax.servletgroupId> 215 <artifactId>servlet-apiartifactId> 216 <version>3.0-alpha-1version> 217 <scope>providedscope> 218 dependency> 219 220 <dependency> 221 <groupId>javax.servletgroupId> 222 <artifactId>jstlartifactId> 223 <version>1.2version> 224 dependency> 225 226 <dependency> 227 <groupId>com.google.guavagroupId> 228 <artifactId>guavaartifactId> 229 <version>19.0version> 230 dependency> 231 <dependency> 232 <groupId>com.google.guavagroupId> 233 <artifactId>guava-collectionsartifactId> 234 <version>r03version> 235 dependency> 236 237 238 <dependency> 239 <groupId>commons-fileuploadgroupId> 240 <artifactId>commons-fileuploadartifactId> 241 <version>1.3.1version> 242 dependency> 243 244 <dependency> 245 <groupId>jaxengroupId> 246 <artifactId>jaxenartifactId> 247 <version>1.1.6version> 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 52 * 就是一个完整的Element 53 * 2.Node代表任意一个节点,可以是上面的Element,也可以是Element中的某个属性 54 * 例如:id="myTestBean"可以是一个Node 55 *测试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 *text 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 Listlist = 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 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 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 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 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 2 <dependency> 3 <groupId>jaxengroupId> 4 <artifactId>jaxenartifactId> 5 <version>1.1.6version> 6 dependency>