【dom4j xml】使用dom4j处理XML文件--测试过程遇到的问题

首先 关于dom4j的API,有如下:

【dom4j  xml】使用dom4j处理XML文件--测试过程遇到的问题

当然  其中的实体引用有以下:

【dom4j  xml】使用dom4j处理XML文件--测试过程遇到的问题

测试使用环境:

使用Maven搭建web环境,pom.xml文件配置如下:

 <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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.it.sxd</groupId>
<artifactId>springModel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<version>3.0</version>
</configuration>
</plugin>
</plugins>
</build> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.4.RELEASE</spring.version>
<hibernate.version>4.3.8.Final</hibernate.version>
</properties> <dependencies>
<!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency> <!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency> <!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency> <!-- 使用SpringMVC需配置 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring cglib 代理 -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency> <!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency> <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency> <!-- 二级缓存ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.9.0</version>
</dependency> <!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency> <!-- mysql连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency> <!-- c3p0数据源 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5-pre10</version>
</dependency> <!-- json --> <!-- 1号 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<!-- 2号 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.1</version>
</dependency> <!-- 3号 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
<exclusions>
<exclusion>
<artifactId>jackson-core</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
<exclusion>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
</exclusions>
</dependency> <!-- 4号 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<!-- 5号 -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- 5号json-lib还需要以下依赖包 -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency> <!-- aop -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency> <!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- guava 集合的交并操作 -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-collections</artifactId>
<version>r03</version>
</dependency> <!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency> </dependencies>
</project>

关于dom4j测试xml文件----实现的代码:

 package com.sxd.dom4j.test;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
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.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test; public class Dom4jTest { @Test
public void mainTest() throws IOException, DocumentException{ // createXML();//创建XML文件
// queryXMLByXPath();//查找XML文件
// queryXMLByDom4j();//查找XML文件
// queryXMLByReadXML();//查找XML文件
updateOdeleteXML();//修改或删除元素
}
/**
* 创建 XML文件
* @throws IOException
*/
public void createXML() throws IOException{
OutputStream out = new FileOutputStream(new File("d:/testXMLFile.xml"));
//XMLWriter生成物理文件
//但是一般生成的xml文件内容比较紧凑
//调用OutputFormat.createPrettyPrint()或者OutputFormat.createCompactFormat()方法可以使XML文件内容格式化输出
XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint()); //Document定义了XML 文档
Document document = DocumentHelper.createDocument(); //设置根节点
Element elementRoot = document.addElement("根节点");
document.setRootElement(elementRoot);
/**
* Element和Node的区别在于:
* 1.Element代表一个对象,对象中有属性,属性有属性值,对象有文本
* 例如:<bean id="myTestBean" class="com.sxd.spring.test1.MyTestBean">测试bean</bean>
* 就是一个完整的Element
* 2.Node代表任意一个节点,可以是上面的Element,也可以是Element中的某个属性
* 例如:id="myTestBean"可以是一个Node
* <bean id="myTestBean" class="com.sxd.spring.test1.MyTestBean">测试bean</bean> 也可以是一个Node
*/ Element element1 = elementRoot.addElement("一层节点");
element1.addAttribute("属性名1","属性值1"); Element element2_1 = element1.addElement("二层节点");
element2_1.addAttribute("id", "attr2_1").addAttribute("name", "attr2_1");
Element element2_2 = element1.addElement("二层节点");
element2_2.addAttribute("id", "attr2_2").addAttribute("name", "attr2_2");
Element element2_3 = element1.addElement("二层节点");
element2_3.addAttribute("id", "attr2_3").addAttribute("name", "attr2_3");
/**
* <beans>text</beans>
*/
element2_2.addText("开始节点和结束节点之间的文本文字");
/**
* 术语 CDATA 指的是不应由 XML 解析器进行解析的文本数据(Unparsed Character Data)。
*/
element2_3.addCDATA("CDATA中的文本 是xml不应该解析的文本数据,一般放置为包含<或者&这种特殊字符的文本"); writer.write(document);
writer.close();
} /**
* 查看 XML文件 使用SAXReader----使用了xpath解析
* @throws DocumentException
*/
public void queryXMLByXPath() throws DocumentException{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("d:/testXMLFile.xml"));
//使用XPath语法 selectNodes()方法得到所有的Element 这里需要Jaxen是一个开源的XPath库
List<Element> list = document.selectNodes("根节点|一层节点|二层节点");
if(!list.isEmpty() && list!=null && list.size()>0){
for (Element element : list) {
just4Element(element);
}
}
} /**
* 递归 抽离element
* @param element
*/
public void just4Element(Element element){
justPlayElement(element);
List<Element> list = element.elements();
if(!list.isEmpty() && list.size()>0 && list!=null){
for (Element e : list) {
just4Element(e);
}
}
} /**
* 重载 展示element信息 默认展示属性信息
* @param element
*/
public void justPlayElement(Element element){
boolean showSon = true;
justPlayElement(element,showSon);
} /**
* 展示element信息
* @param element
*/
public void justPlayElement(Element element,boolean showSon){
System.out.println("节点名称:"+element.getName());
System.out.println("节点文本:"+element.getText());
int attributeSum = element.attributeCount();
System.out.println("节点属性个数:"+attributeSum);
//或者
if(showSon){
List<Attribute> attList = element.attributes();
if(attList!= null && attList.size()>0){
for (Attribute attribute : attList) {
System.out.println("节点"+element.getName()+"的属性->"+attribute.getName()+":"+attribute.getValue());
}
}
} System.out.println("----------------------------------------------------------------------------------------"); } /**
* 查看 XML文件 使用SAXReader --纯dom4j解析
* @throws DocumentException
*/
public void queryXMLByDom4j() throws DocumentException{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("d:/testXMLFile.xml"));
//先得到根节点
Element element = document.getRootElement();
if(element!= null){//然后调用递归 去取出 根节点中所有结点信息
just4Element(element);
}
} /**
* 查看 XML文件 通过读取XML字符串的方式
* @throws IOException
* @throws DocumentException
*/
public void queryXMLByReadXML() throws IOException, DocumentException{
File file = new File("d:/testXMLFile.xml");
List<String> list = Files.readAllLines(file.toPath());
StringBuilder xmlStr = new StringBuilder();//优先使用StringBuilder[单线程 速度更快]
for (String string : list) {
xmlStr.append(string);
}
//将字符串转化为XML
Document document = DocumentHelper.parseText(xmlStr.toString());
//先得到根节点
Element element = document.getRootElement();
if(element!= null){//然后调用递归 去取出 根节点中所有结点信息
just4Element(element);
}
} /**
* 修改XML文件内容
* @throws DocumentException
* @throws IOException
*/
public void updateOdeleteXML() throws DocumentException, IOException{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("d:/testXMLFile.xml"));
Element elementRoot = document.getRootElement();
Element element = (Element) elementRoot.selectSingleNode("一层节点");
justPlayElement(element,true);//调用 展示标签信息 不展示子层信息 element.addAttribute("属性名2", "属性值2");
element.addText("一层节点的文本 是修改之后的结果");
element.setAttributeValue("属性名1", "修改之后的属性值1");//Deprecated. As of version 0.5. Please use addAttribute(QName, String) instead. WILL BE REMOVED IN dom4j-1.6 !!
element.addAttribute("属性名1", "二次修改之后的属性值1"); justPlayElement(element);//展示 修改之后的 元素信息 List<Element> elements = element.elements();
for (Element element2 : elements) {
if(element2.attributeValue("id").equals("attr2_1")){
element2.getParent().remove(element2);
}
} OutputStream outputStream = new FileOutputStream("d:/testXMLFile.xml");
XMLWriter writer = new XMLWriter(outputStream, OutputFormat.createPrettyPrint());
writer.write(document);
writer.close(); } }

查询所有的展示结果:

【dom4j  xml】使用dom4j处理XML文件--测试过程遇到的问题

在测试过程中有如下的错误:

错误1:

 错误1:
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: 根节点
at org.dom4j.tree.AbstractDocument.checkAddElementAllowed(AbstractDocument.java:241)
at org.dom4j.tree.AbstractDocument.add(AbstractDocument.java:203)
at org.dom4j.tree.AbstractDocument.addElement(AbstractDocument.java:173)
at com.sxd.dom4j.test.Dom4jTest.createXML(Dom4jTest.java:52)
at com.sxd.dom4j.test.Dom4jTest.mainTest(Dom4jTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

解决方法:

【dom4j  xml】使用dom4j处理XML文件--测试过程遇到的问题

错误2:

 报错2:
java.lang.NoClassDefFoundError: org/jaxen/NamespaceContext
at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164)
at com.sxd.dom4j.test.Dom4jTest.queryXMLBySAXReader(Dom4jTest.java:87)
at com.sxd.dom4j.test.Dom4jTest.mainTest(Dom4jTest.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: org.jaxen.NamespaceContext
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 28 more

解决方法:

【dom4j  xml】使用dom4j处理XML文件--测试过程遇到的问题

Maven路径:

 <!--  https://mvnrepository.com/artifact/jaxen/jaxen -->
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
上一篇:跟随 Web 标准探究DOM -- Node 与 Element 的遍历


下一篇:JavaScript 语言基础