1.Dom4j 解析xml
package com.imooc.dom4j;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class HrReader {
public void readXml() {
String file = "D:\\software\\Eclipse\\eclipse workspace\\xml\\src\\hr.xml";
//SAXReader类是读取xml文件的核心类,用于将xml解析后,以树的形式保存在内存中
SAXReader reader = new SAXReader();
try {
Document document = reader.read(file);
//获取xml的根节点
Element root = document.getRootElement();
//elements 用于获取指定的标签集合
List<Element> employees = root.elements("employee");
for(Element employee:employees) {
//element 方法用于获取唯一的子节点对象
Element name = employee.element("name");
String empName = name.getText();//用于获取标签文本
System.out.println(empName);
System.out.println(employee.elementText("age"));//直接获取标签中的文本信息
System.out.println(employee.elementText("salary"));
Element department = employee.element("department");
System.out.println(department.elementText("dname"));
//获取属性
Attribute att = employee.attribute("no");
System.out.println(att.getText());
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
HrReader reader = new HrReader();
reader.readXml();
}
}
2.更新xml
package com.imooc.dom4j;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class HrWriter {
String file = "D:\\software\\Eclipse\\eclipse workspace\\xml\\src\\hr.xml";
public void writeXml() {
SAXReader reader = new SAXReader();
Document document;
try {
document = reader.read(file);
Element root = document.getRootElement();
Element employee = root.addElement("employee");
employee.addAttribute("no", "233");
Element name = employee.addElement("name");
name.setText("王五");
employee.addElement("age").setText("34");
employee.addElement("salary").setText("5000");
Element department = employee.addElement("department");
department.addElement("dname").setText("人事部");
department.addElement("address").setText("xx大厦-B1201");
//将数据从内存写入xml文件
Writer writer = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
document.write(writer);
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
HrWriter hrWriter = new HrWriter();
hrWriter.writeXml();
}
}