package forXML;
import java.io.File;
import java.io.FileOutputStream;
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.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4jParser {
/**
* 最后一发实验报告~~~~啦啦啦~~祝高分通过~~~
*
* @author catfish
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// 获取解析器
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(new File("src/forXML/employee.xml"));
travel(doc.getRootElement());
System.out.println("-----我是最可爱的分界线----");
add(doc);
update(doc);
travel(doc.getRootElement());
}
//更新xml文件
public static void update(Document doc) throws Exception {
// TODO Auto-generated method stub
Iterator iter = doc.getRootElement().elementIterator("employee");
while (iter.hasNext()) {
Element employee = (Element) iter.next();
Element emp_name = (Element) employee.elements("name").get(0);
if (emp_name.getTextTrim().equals("孙二狗")) {
Element emp_pay = employee.element("monthly_pay");
emp_pay.addAttribute("mode", "credit_card");
emp_pay.setText("2300");
}
}
// OutputFormat.createCompactFormat() 紧凑格式
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream(new File("src/dom4j/class.xml")), format);
writer.write(doc);
writer.close();
}
//添加一个节点
public static void add(Document doc) throws Exception {
// TODO Auto-generated method stub
Element newPlo = DocumentHelper.createElement("employee");
newPlo.addAttribute("sn", "E-30000232323022");
Element newPlo_name = DocumentHelper.createElement("name");
newPlo_name.setText("宋猪头");
newPlo.add(newPlo_name);
Element newPlo_age = DocumentHelper.createElement("age");
newPlo_age.setText("26");
newPlo.add(newPlo_age);
Element newPlo_pay = DocumentHelper.createElement("monthly_pay");
newPlo_pay.addAttribute("mode", "cash");
newPlo_pay.setText("1900");
newPlo.add(newPlo_pay);
doc.getRootElement().add(newPlo);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream(new File("src/forXML/employee.xml")), format);
writer.write(doc);
writer.close();
}
//遍历xml文件
public static void travel(Element element) {
// TODO Auto-generated method stub
System.out.println(element.getName() + ": " + element.getTextTrim());
List list = element.attributes();
for (int i = 0; i < list.size(); i++) {
Attribute attri = (Attribute) list.get(i);
System.out.println(attri.getName() + ": " + attri.getText());
}
Iterator iterator = element.elementIterator();
while (iterator.hasNext()) {
Element el = (Element) iterator.next();
travel(el);
}
}
}
把下面依赖的jar包导入java project–>Build Path–>Configure Build Path–>Add External JARs,然后选中下面连接中下载好的jar包,最后点击Apply