// 输出文件
File outputFile = new File(outputPath);
try {
// 美化格式
OutputFormat format = OutputFormat.createPrettyPrint();
// 指定XML编码,不指定的话,默认为UTF-8
format.setEncoding("UTF-8");
XMLWriter output = new XMLWriter(new FileWriter(outputFile), format);
output.write(doc);
output.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
/**
* 普通方法遍历xml
*
* @param doc
*/
public void traversalDocumentByElementIterator(Document doc) {
// 获取根节点
Element root = doc.getRootElement();
// 枚举根节点下所有子节点
for (Iterator ie = root.elementIterator(); ie.hasNext();) {
System.out.println("======");
Element element = (Element) ie.next();
System.out.println(element.getName());
// 枚举属性
for (Iterator ia = element.attributeIterator(); ia.hasNext();) {
Attribute attribute = (Attribute) ia.next();
System.out.println(attribute.getName() + ":"
+ attribute.getData());
}
// 枚举当前节点下所有子节点
for (Iterator ieson = element.elementIterator(); ieson.hasNext();) {
Element elementSon = (Element) ieson.next();
System.out.println(elementSon.getName() + ":"
+ elementSon.getText());
}
}
}
/**
* 使用elements方法进行xml的读取,相当于条件查询,可以根据不同的节点,利用for循环查询该节点下所有的数据。
*
* @throws DocumentException
*/
public static void traversalDocumentByElements(Document doc) {
// 获取根节点
Element root = doc.getRootElement();
// 根据根节点,将根节点下 student中的所有数据放到list容器中。
List list = root.elements("student");
// 这种遍历方式,是jdk1.5以上的版本支持的遍历方式,嘿嘿试试
for (Object obj : list) {
Element el = (Element) obj;
System.out.println("----------"+el.getName()+"-----------");
// 获取name节点下所有的内容,存入listName容器中
List listName = el.elements("name");
// 获取age节点下所有的内容,存入age容器中
List listAge = el.elements("age");
for (int i=0;i
// 获取name节点下的数据。
System.out.println(elname.getName() + ": " + elname.getText());
Element elage = (Element) listAge.get(i);
// 获取age节点下的数据。
System.out.println(elage.getName() + ": " + elage.getText());
}
}
}
/**
* 使用selectNodes读取xml文件
*
* @param args
* @throws DocumentException
*/
public static void traversalDocumentByselectNodes(Document doc,
String elementpath) {
// 使用selectNodes获取所要查询xml的节点。
List list = doc.selectNodes(elementpath);
// 遍历节点,获取节点内数据。
for (Iterator ie = list.iterator(); ie.hasNext();) {
Element el = (Element) ie.next();
System.out.println(el.getName() + ": " + el.getText());
}
}
/**
* 基于访问者模式遍历
*
* @param doc
*/
public void traversalDocumentByVisitor(Document doc) {
doc.accept(new MyVisitor());
}
}
MyVisitor.java
[java]
package com.jialin;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.dom4j.ProcessingInstruction;
import org.dom4j.VisitorSupport;
/**
* 定义自己的访问者类
*/
public class MyVisitor extends VisitorSupport {
/**
* 对于属性节点,打印属性的名字和值
*/
public void visit(Attribute node) {
System.out.println("attribute : " + node.getName() + " = "
+ node.getValue());
}
/**
* 对于处理指令节点,打印处理指令目标和数据
*/
public void visit(ProcessingInstruction node) {
System.out.println("PI : " + node.getTarget() + " "
+ node.getText());
}
/**
* 对于元素节点
* 如果包含文本内容,则打印元素的名字和元素的内容