dom4j解析crud

        在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();
}

}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值