1 import java.io.FileWriter; 2 import java.io.IOException; 3 import java.util.List; 4 5 import org.dom4j.Document; 6 import org.dom4j.Element; 7 import org.dom4j.io.OutputFormat; 8 import org.dom4j.io.SAXReader; 9 import org.dom4j.io.XMLWriter; 10 11 /** 12 * 13 * a 性能好 b 操作方便 c 功能强大 14 * 15 * 16 * @author Jxy 17 * 18 */ 19 public class Dom4jTest { 20 21 public static void main(String[] args) throws Exception { 22 SAXReader reader = new SAXReader(); 23 Document document = reader.read("NewFile.xml"); 24 25 Element root = document.getRootElement(); 26 System.out.println(root.getName()); 27 @SuppressWarnings("unchecked") 28 List<Element> elements = root.elements(); 29 30 for (Element element : elements) { 31 System.out.println("元素名称: " + element.getName()); 32 Element name = element.element("name"); 33 System.out.println(name.getText()); 34 } 35 36 // 增加节点 37 38 Element student = root.addElement("student"); 39 student.addAttribute("id", "3"); 40 Element name = student.addElement("name"); 41 name.setText("ganlun"); 42 Element age = student.addElement("age"); 43 age.setText("66"); 44 toParserDemo(document); 45 // 修改节点 46 Element element = root.element("student"); 47 element.element("name").setText("jiaohao"); 48 49 // 删除节点 50 root.remove(element); 51 52 } 53 54 public static void toParserDemo(Document document) throws IOException { 55 // 转换dom对象为xml文档 56 OutputFormat format = new OutputFormat(); 57 format.setEncoding("UTF-8"); 58 XMLWriter xmlWriter = new XMLWriter(new FileWriter("NewFIle.xml"), format); 59 xmlWriter.write(document); 60 xmlWriter.close(); 61 } 62 63 }