这是一个添加一组数据的案例:
为第一个学生添加学校
src/stu.xml
<?xml version="1.0" encoding="UTF-8"?> <exam> <student> <name>张三</name> <location>西安</location> <grade>98</grade> </student> <student> <name>李四</name> <location>临潼</location> <grade>59</grade> </student> </exam>
Add.java
package Dom4j; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; 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 Add { public static void main(String[]args) throws DocumentException,IOException { SAXReader reader = new SAXReader(); Document document = reader.read("src/stu.xml"); Element root = document.getRootElement(); Element student=root.element("student"); student.addElement("学校").addText("西瓜大"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter( new FileOutputStream("src/stu.xml"),format ); writer.write( document ); writer.close(); } }dom4j中获取一个元素的子元素可以调用element方法。 若调用elements方法会返回list,即所有节点。 原文链接:https://www.f2er.com/xml/294882.html