(四)使用dom4j方式操作xml
dom4j是解析XML的一种开源API,是jdom的升级品,用来读写XML文档。它具有性能优异、功能强大和极易使用的特点,它的性能超过sun公司官方的dom技术。dom4j对Xpath有良好的支持(使用xpath时需要导入jaxen的jar包),dom4j最大的特色使用大量的接口。使用dom4j时需要导入dom4j-xxx.jar包。
Attribute ——Attribute定义了XML的属性
Branch ——Branch为能够包含子节点的节点如XML元素(Element)和文档(Docuemnts)定义了一个公共的行为,
CDATA ——CDATA 定义了XML CDATA 区域
CharacterData——CharacterData是一个标识接口,标识基于字符的节点。如CDATA,Comment, Text.
Comment—— Comment 定义了XML注释的行为
Document—— 定义了XML文档
DocumentType—— DocumentType 定义XML DOCTYPE声明
Element—— Element定义XML 元素
ElementHandler ——ElementHandler定义了 Element 对象的处理器
ElementPath 被 ElementHandler 使用,用于取得当前正在处理的路径层次信息
Entity ——Entity定义 XML entity
Node ——Node为所有的dom4j中XML节点定义了多态行为
NodeFilter ——NodeFilter 定义了在dom4j节点中产生的一个滤镜或谓词的行为(predicate)
ProcessingInstruction ——ProcessingInstruction 定义 XML 处理指令.
Text ——Text 定义XML文本节点.
Visitor—— Visitor 用于实现Visitor模式.
XPath ——XPath 在分析一个字符串后会提供一个Xpath表达式
测试类代码:
public class Dom4jTest {
private Document doc;
@Before
public void setUp() throws Exception {
// 获得xml文档的输入流对象
InputStream is = Dom4jTest.class.getClassLoader().getResourceAsStream("books.xml");
// 创建SAXReader对象
SAXReader reader = new SAXReader();
// 通过流对象解析xml文档为Document对象
doc = reader.read(is);
}
/**
* 使用节点迭代器查询元素
* @throws Exception
*/
@Test
public void testRetrieve() throws Exception {
//获得文档的根节点
Element rootElement = doc.getRootElement();
Iterator iterator = rootElement.elementIterator();
while(iterator.hasNext()){
//获得子节点,先转换为Element,有更多的方法
Element element = (Element) iterator.next();
String value = element.attributeValue("category");
//获得属性为CHILDREN的book节点
if("CHILDREN".equals(value)){
//获得book节点的迭代器
Iterator childIterator = element.elementIterator();
while(childIterator.hasNext()){
Node node = (Node) childIterator.next();
//获取子节点的名称
String name = node.getName();
if("price".equals(name)){
//获取节点的文本
String text = node.getText();
System.out.println(text);
}
}
}
}
}
/**
* 使用访问器来读取xml文档节点
* @throws Exception
*/
@Test
public void testRetrieveByVisitor() throws Exception{
//获得xml文档的输入流对象
InputStream is = Dom4jTest.class.getClassLoader().getResourceAsStream("books.xml");
// 创建SAXReader对象
SAXReader reader = new SAXReader();
// 通过流对象解析xml文档为Document对象
Document doc = reader.read(is);
// 获得文档的根节点
Element rootElement = doc.getRootElement();
//创建自定义的Visitor对象
Visitor visitor = new DomVisitor();
//使用visitor查询文档
rootElement.accept(visitor);
}
/**
* 创建新的xml文档
* @throws Exception
*/
@Test
public void testCreate() throws Exception{
//第一种,创建Document的方法(org.dom4j.Document)
//第一种创建方式是对第二种创建方式的封装
Document document = DocumentHelper.createDocument();
//第二种,创建Document的方法(org.dom4j.Document)
//Document doc = DocumentFactory.getInstance().createDocument();
//创建根元素节点
Element rootElement = document.addElement("bookstore");
//创建book节点及其子节点
Element bookElement = rootElement.addElement("book");
bookElement.addAttribute("CATEGORY", "CODING");
Element title=bookElement.addElement("title");
title.setText("JAVA CODING");
Element author=bookElement.addElement("author");
author.setText("zs");
Element year=bookElement.addElement("year");
year.setText("2010");
Element price=bookElement.addElement("price");
price.setText("69");
//打印到控制台
writeToConsole(document);
//输出到文件
writeToFile(document);
}
//输出到文件
private void writeToFile(Document document) throws IOException {
//创建美化格式
OutputFormat format=OutputFormat.createPrettyPrint();
XMLWriter writer=new XMLWriter
(new FileWriter(new File("abook.xml")),format);
writer.write(document);
//关闭writer就会清空缓存
writer.close();
}
//打印到控制台
private void writeToConsole(Document document) throws IOException {
//创建输出字符流
PrintWriter writer=new PrintWriter(System.out);
document.write(writer);
//关闭writer就会清空缓存,才会输出来
writer.close();
}
/**
* 使用XPath查找节点,xpath序号从1开始
* 要使用dom4j的xpath支持,需要导入jaxen包
*/
@Test
public void testXPath() throws Exception{
//获得属性web的book节点
Node node = doc.selectSingleNode("//book[@category='WEB']");
//获得所有的book节点
List nodes = doc.selectNodes("//book");
//获得第2个book节点
Node secondNode = doc.selectSingleNode("//book[2]");
//将xml片段转换为字符串
String xml = secondNode.asXML();
System.out.println(xml);
}
@Test
public void testStringToXML() throws Exception{
String xmlString="<book category='CHILDREN'><title lang='en'>Harry Potter</title>"+
"<author>J K. Rowling</author><year>2005</year><price>29.99</price></book>";
//转换字符串为xml片段
Document document = DocumentHelper.parseText(xmlString);
//打印到控制台
writeToConsole(document);
}
/**
* 删除指定的节点
* @throws Exception
*/
@Test
public void testDelete() throws Exception{
//获得最后一个book节点
Node node = doc.selectSingleNode("//book[4]");
//获得最后一个book节点的父节点
Element parent = node.getParent();
//删除最后一个book节点,删除需要使用父节点来删除,删除成功则返回true
Boolean flag=parent.remove(node);
System.out.println(flag);
//打印到控制台
writeToConsole(doc);
}
/**
* 修改指定的节点
* @throws Exception
*/
@Test
public void testUpdate() throws Exception{
//获得第一个book节点的price和year
Node yearNode = doc.selectSingleNode("//book[1]/year");
yearNode.setText("2015");
Node priceNode = doc.selectSingleNode("//book[1]/price");
priceNode.setText("59.00");
//修改后的xml文档打印到控制台
writeToConsole(doc);
}
} Visitor子类代码:
public class DomVisitor extends VisitorSupport {
// 使用栈这个数据结构来保存
private Stack<String> stack = new Stack<String>();
// 数据
private String attr;
private String title;
private String author;
private String year;
private double price;
@Override
public void visit(Document document) {
}
@Override
public void visit(Element node) {
// System.out.println("element node-----------");
//获得节点的名称
String name = node.getName();
if("book".equals(name)){
if(!stack.isEmpty()){
stack.clear();
}
stack.push(name);
}else if("title".equals(node.getName())){
stack.push(name);
}else if("author".equals(name)){
stack.push(name);
}else if("year".equals(name)){
stack.push(name);
}else if("price".equals(name)){
stack.push(name);
}
}
@Override
public void visit(Attribute node) {
// System.out.println("attribute node-----");
String peek = stack.peek();
if("book".equals(peek)){
String value = node.getValue();
if("CHILDREN".equals(value)){
attr=value;
}
}
}
@Override
public void visit(Text node) {
// System.out.println("text node--------");
//注意:一个标签元素前后都有一个文本节点
if("CHILDREN".equals(attr)){
String tag = stack.peek();
if ("title".equals(tag) && null==title)
{
title = node.getText();
}
else if ("author".equals(tag) && null==author)
{
author = node.getText();
}
else if ("year".equals(tag) && null==year)
{
year = node.getText();
}
else if ("price".equals(tag) && price==0)
{
price = Double.parseDouble(node.getText());
System.out.println(this.toString());
}
}
}
@Override
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append("book attribute:"+attr);
sb.append("\n");
sb.append("title:"+title);
sb.append("\n");
sb.append("author:"+author);
sb.append("\n");
sb.append("year:"+year);
sb.append("\n");
sb.append("price:"+price);
sb.append("\n");
return sb.toString();
}
} 使用Visitor子类读取文档结果:
book attribute:CHILDREN
title:Harry Potter
author:J K. Rowling
year:2005