在shuiguo.xml文件中的水果中的苹果节点中添加节点<小苹果>small apple</小苹果>,添加小苹果后将其文本内容修改为“小苹果”,修改该节点后将其父节点苹果(即第三个苹果元素)删除掉。
package com.xml.dom4j;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
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 Dom4jTest {
public static void main(String[] args) throws Exception {
SAXReader reader=new SAXReader();
Document doc=reader.read(new File("src/shuiguo.xml"));
Element root=(Element) doc.getRootElement();
addTest(root,doc);//添加
//updateTest(root,doc);//修改元素文本
//deleteTest(root,doc);
}
public static void listTest(Element root) {
System.out.println(root.getName());
List<Element> list=root.elements();
for(Element child:list){
listTest(child);
}
}
public static void deleteTest(Element root, Document doc) {
Element apple=root.element("水果").element("苹果");
apple.getParent().remove(apple);
writerFile(doc);
}
public static void updateTest(Element root, Document doc) {
Element smallapple=root.element("水果").element("苹果").element("小苹果");
smallapple.setText("小苹果");
writerFile(doc);
}
public static void addTest(Element root, Document doc) {
List list=root.element("水果").element("苹果").elements();
Element smallapple=DocumentHelper.createElement("小苹果");
smallapple.setText("small apple");
list.add(0,smallapple);
writerFile(doc);
}
public static void writerFile(Document doc) {
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
try {
XMLWriter writer = new XMLWriter(new FileWriter("src/shuiguo.xml"),format);
writer.write(doc);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}