前言
最近再看mybatis框架中,我们知道底层中,好多xml都是通过dom4j来解析。为了回顾以前的知识点,重新来认识了一下dom4j。
二话不说直接来上代码
首先先建立一个配置文件,让dom4j来进行解析我们就随便建立了一个。
user.xml
<hibernate-mapping>
<class name="com.test.user" table="userTabel">
<property name="userName" value="李三"></property>
<property name="password" value="密码"></property>
</class>
</hibernate-mapping>
然后是我们的读取类 XmlParse
package com.test.xml;
import org.dom4j.Document;
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 java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
public class XmlParse {
public static void main(String[] args) {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
//读取配置文件
document = saxReader.read(new File("user.xml"));
//获取根节点
Element rootElement = document.getRootElement();
//获取根节点的下的元素
Element classElement = rootElement.element("class");
//根据属性名获取值
String name = classElement.attributeValue("name");
String table = classElement.attributeValue("table");
System.out.println("class"+":"+name+",table:"+table);
List<Element> elements = classElement.elements();
for (Element propElement:elements) {
String userName = propElement.attributeValue("name");
String value = propElement.attributeValue("value");
System.out.println("userName:"+userName+",value:"+value);
}
//xpath
List<Node> xPathList = document.selectNodes("//hibernate-mapping/class/property");
for (Node n:xPathList) {
String userName = n.getName();
String names = n.valueOf("@name");
String value = n.valueOf("@value");
System.out.println("userName:"+names+",value:"+value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是执行的结果用两种方式执行了一下。一种是xpath这个需要加入第三方jar包的。
下面再来一种生成xml的方式。
public static Document createDocument(){
Document document = DocumentHelper.createDocument();
Element root = document.addElement("hibernate-mapper");
Element classElement = root.addElement("class")
.addAttribute("name", "com.guo.user")
.addAttribute("table", "user");
classElement.addElement("property")
.addAttribute("name","username")
.addAttribute("value","李三");
classElement.addElement("property")
.addAttribute("name","password")
.addAttribute("value","密码");
try {
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(new FileWriter("user1.xml"),format);
writer.write(document);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
return document;
}
来源:https://blog.csdn.net/a913858/article/details/98994301