package dom;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class DomOperate{
public static void main(String[] args) {
try {
File file=new File("f://test/dom.xml");
SAXReader reader=new SAXReader();
Document document=reader.read(file);
Element root=document.getRootElement();
/*
* 遍历节点
*/
List<Element> list=root.elements("user");
Iterator<Element> it=list.iterator();
while(it.hasNext()){
Element element=it.next();
System.out.println(element.elementText("name"));
}
//addNode(file, document, root);//添加节点
//deleteNode(file, document, root);//删除节点
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* 删除节点
* @param file
* @param document
* @param root
*/
private static void deleteNode(File file, Document document, Element root) {
Element element=root.element("add");
element.getParent().remove(element);
submit(file, document);
System.out.println("del success");
}
/**
* 添加节点
* @param file
* @param document
* @param root
*/
private static void addNode(File file, Document document, Element root) {
Element element=root.addElement("add");
element.setText("测试添加");
submit(file, document);
System.out.println("add success");
}
/**
* 保存xml
* @param file
* @param document
* @throws IOException
*/
private static void submit(File file, Document document) {
try {
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer=new XMLWriter(new FileWriter(file));
writer.write(document);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
dom.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<user>
<name>张三</name>
<age>12</age>
</user>
<user>
<name>李四</name>
<age>15</age>
</user>
</root>
jar包:dom4j-1.6.1.jar