下面是写文章用的代码:
package xmloperate;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
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.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
*
* @ClassName: XMLOperateDOM4J
* @Description: DOM4J操作XML文件详解
* @author 刘东东
* @date 2010-7-6 下午10:16:40
*
*/
public class XMLOperateDOM4J {
/**
* 通过读取XML文件,返回一个XML文档对象
* @param pathXML XML文件路径
* @return Document对象
* @throws DocumentException 获取Document对象时出现的异常
*/
public Document getDocObjByFile(String pathXML) throws DocumentException {
SAXReader reader = new SAXReader(); //SAXReader主要用于解析XML文件
Document document = reader.read(new File(pathXML)); //从指定的文件中读取Document
return document;
}
/**
* 通过读取XML文本,返回一个XML文档对象
* @param textXML XML文本
* @return Document对象
* @throws DocumentException 获取Document对象时出现的异常
*/
public Document getDocObjByText(String textXML) throws DocumentException {
//DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类
//将textXML解析为一个XML文档并返回一个新创建的Document
Document document = DocumentHelper.parseText(textXML);
return document;
}
/**
* 自动创建一个Document对象,主要用于创建XML文件时使用
* @return Document对象
*/
public Document getDocObjByAuto() {
//创建一个Document对象
Document document = DocumentHelper.createDocument();
return document;
}
/**
* 读取XML文件并遍历根节点下的子节点
* @param pathXML XML文件路径
* @throws DocumentException 获取Document对象时出现的异常
*/
public void readXMLByFile(String pathXML) throws DocumentException {
Document document = getDocObjByFile(pathXML);
if (document != null) {
Element root = document.getRootElement(); //获取根节点
//遍历根节点下的子节点
for (Iterator it = root.elementIterator(); it.hasNext();) {
Element child = (Element) it.next();
String name = child.getName(); //获取节点的名字
String text = child.getText(); //读取节点的内容
System.out.println("节点名:" + name + " 内容:" + text);
}
System.out.println("====================================================================");
//遍历根节点下指定的子节点a
for (Iterator it = root.elementIterator("a"); it.hasNext();) {
Element child = (Element) it.next();
String name = child.getName(); //获取节点的名字
String text = child.getText(); //读取节点的内容
System.out.println("节点名:" + name + " 内容:" + text);
}
System.out.println("====================================================================");
//遍历根节点的子节点的属性id
for (Iterator it = root.elementIterator(); it.hasNext();) {
Element child = (Element) it.next();
String name = child.getName(); //获取节点的名字
Attribute att = child.attribute("id"); //获取属性id
String text1 = att.getText(); //读取属性的值
System.out.println("方法一 节点名:" + name + " 属性id:[ " + text1 + " ]");
String text2 = child.attributeValue("id"); //读取属性的值
System.out.println("方法二 节点名:" + name + " 属性id:[ " + text2 + " ]");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
//遍历f节点的所有属性
Element elf = root.element("f"); //获取指定的节点f
System.out.println("方法一:" + elf.getText()); //方法一:获取指定节点的内容
System.out.println("方法二:" + root.elementText("f")); //方法二:获取指定节点的内容
System.out.println("----------------------------------------------------");
for (Iterator it = elf.attributeIterator(); it.hasNext();) {
Attribute att = (Attribute) it.next();
String name = att.getName(); //获取属性名字
String text = att.getText(); //获取属性值
System.out.println("属性名:" + name + " 属性值:" + text);
}
System.out.println("====================================================================");
//遍历d节点的所有子节点 方法一:
Element eld = root.element("d"); //获取指定的节点
for (Iterator it = eld.elementIterator(); it.hasNext();) {
Element el = (Element) it.next();
String name = el.getName();
String text = el.getText();
System.out.println("方法一 节点名:" + name + " 内容:" + text);
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
//遍历d节点的所有子节点 方法二:
List eld1 = root.selectNodes("/root/d/*"); //获取指定的节点
for (Iterator it = eld1.iterator(); it.hasNext();) {
Node el = (Node) it.next();
String name = el.getName();
String text = el.getText();
System.out.println("方法二 节点名:" + name + " 内容:" + text);
}
System.out.println("====================================================================");
//遍历d节点中d2子节点的所有属性
Element eld2 = root.element("d").element("d2"); //获取指定的节点
for (Iterator it = eld2.attributeIterator(); it.hasNext();) {
Attribute att = (Attribute) it.next();
String name = att.getName();
String text = att.getText();
System.out.println("属性名:" + name + " 属性值:" + text);
}
System.out.println("====================================================================");
//遍历d1节点下的子节点d11 方法一:
List d11 = root.element("d").element("d1").elements("d11");
for (Iterator it = d11.iterator(); it.hasNext();) {
Element child = (Element) it.next();
String name = child.getName(); //获取节点的名字
String text = child.getText(); //读取节点的内容
System.out.println("方法一 节点名:" + name + " 内容:" + text);
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
//遍历d1节点下的子节点d11 方法二:
List nodes = root.selectNodes("/root/d/d1/d11");
for (Iterator it = nodes.iterator(); it.hasNext();) {
Node child = (Node) it.next();
String name = child.getName(); //获取节点的名字
String text = child.getText(); //读取节点的内容
System.out.println("方法二 节点名:" + name + " 内容:" + text);
}
System.out.println("====================================================================");
//根据属性id遍历某节点
List elb2 = root.selectNodes("/root/b[@id='b2']");
for (Iterator it = elb2.iterator(); it.hasNext();) {
Node b2 = (Node) it.next();
String name = b2.getName();
String text = b2.getText();
String id = b2.valueOf("@id"); //得到属性id的值
System.out.println("节点名:" + name + " 内容:" + text + " id:" + id);
}
System.out.println("====================================================================");
//根据属性id遍历某节点的子节点
List eldd = root.selectNodes("/root/d[@id='d1']/*");
for (Iterator it = eldd.iterator(); it.hasNext();) {
Node b2 = (Node) it.next();
String name = b2.getName();
String text = b2.getText();
String id = b2.valueOf("@id");
System.out.println("节点名:" + name + " 内容:" + text + " id:" + id);
}
System.out.println("====================================================================");
//根据指定条件快速获取某个节点
Node node = root.selectSingleNode("/root/d[@name='d22']");
System.out.println(node.asXML()); //将获取的节点转换成字符串
System.out.println("id: " + node.valueOf("@id") + " name: " + node.valueOf("@name") + " 内容: " + node.getText());
System.out.println("====================================================================");
//递归遍历某个节点
recursive(root);
}
}
/**
* 读取XML文本并遍历节点
* @param textXML XML文本
* @throws DocumentException 获取Document对象时出现的异常
*/
public void readXMLByText(String textXML) throws DocumentException {
Document doc = getDocObjByText(textXML);
if (doc != null) {
Element root = doc.getRootElement();
for (Iterator it = root.elementIterator(); it.hasNext();) {
Element el = (Element)it.next();
System.out.println("节点名:" + el.getName() + " 内容:" + el.getText() + " id: " +
el.attributeValue("id") + " name: " + el.attributeValue("name"));
}
}
}
/**
* 递归遍历某个节点
* @param element 显示内容的节点
*/
public void recursive(Element element) {
for (int i = 0, size = element.nodeCount(); i < size; i++) {
Node node = element.node(i);
if (node instanceof Element) {
recursive((Element) node);
} else {
System.out.println("##" + "==" + node.getText());
}
}
}
/**
* 写XML文件
*/
public void writeXML(){
try {
Document doc = getDocObjByAuto();
//添加文档类型说明,读取XML文件时,文档类型说明一定要存在,否则会报错
//doc.addDocType("root" , null , "file://c:/Dtds/catalog.dtd" );
Element root = doc.addElement("root"); //添加根元素
root.addComment("这是注解"); //添加一个注解
//添加a元素,并指定内容
root.addElement("a").addText("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); //或用setText();
Document document = getDocObjByFile("d:/menu.xml");
Element elef = document.getRootElement().element("f"); //获取f元素
root.add((Element)elef.clone()); //将获取到的f元素添加的新建的XML文件中
Element d = root.addElement("d"); //添加d元素
Element el = document.getRootElement().element("d").element("d2"); //获取d2元素
d.addAttribute("id", "d1"); //添加id属性
d.addAttribute("name", "d11"); //添加name属性
//添加d1和d11元素,并给d11元素指定内容
d.addElement("d1").addElement("d11").setText("d11d11d11d11d11d11d11d11d11d11");
Element d2 = d.addElement("d2"); //添加d2元素
d2.add((Attribute)el.attribute("id").clone()); //添加id属性
d2.add((Attribute)el.attribute("name").clone()); //添加name属性
d2.add((Attribute)el.attribute("type").clone()); //添加type属性
d2.setText("d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK" ); // 指定XML编码
format.setIndent(" "); //根据给定的设置缩进(四个空格)<=>setIndentSize(4), 或可用setIndent(true)
XMLWriter writer = new XMLWriter(new FileWriter("d:/menu1.xml"), format);
writer.write(doc); //将XML文件写到指定的位置
writer.close();
System.out.println("输出成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 对XML进行修改、删除操作
* @param pathXML XML文件路径
*/
public void updateAndDelete(String pathXML) {
try {
Document document = getDocObjByFile(pathXML);
if (document != null) {
Element root = document.getRootElement();
Element a = root.element("a");
a.addAttribute("id", "a1"); //为a元素添加属性id
a.setText("11111111111111111111111111"); //修改a元素的内容
Element d2 = root.element("d").element("d2");
d2.attribute("name").setValue("88888"); //修改d2的name属性
Element elef = root.element("f");
elef.remove(elef.attribute("type")); //删除f元素的type属性
Element d = root.element("d");
d.remove(d.element("d1")); //删除d1元素
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK" ); // 指定XML编码
format.setIndent(" "); //根据给定的设置缩进(四个空格)<=>setIndentSize(4), 或可用setIndent(true)
XMLWriter writer = new XMLWriter(new FileWriter("d:/menu11.xml"), format);
writer.write(document); //将XML文件写到指定的位置
writer.close();
System.out.println("修改成功!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
XMLOperateDOM4J xml = new XMLOperateDOM4J();
try {
xml.readXMLByFile("d:/menu.xml");
StringBuffer buffer = new StringBuffer(1000);
buffer.append("<?xml version=/"1.0/" encoding=/"UTF-8/"?>/r<root>/r")
.append("<d id=/"d2/" name=/"d22/">d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2</d>")
.append("/r</root>/r");
xml.readXMLByText(buffer.toString());
xml.writeXML();
xml.updateAndDelete("d:/menu1.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
}