Dom4j修改文件

package com.beckham.dom; import java.io.File; import java.io.FileWriter; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; /** * @author 作者<Beckham> Email:gaowm0207@gmail.com Jan 29, 2010 10:16:55 AM * Version:1.0 修改XML文件 */ public class ModifyXML { public static void main(String[] args)throws Exception { createFile("src/com/beckham/dom/student.xml") ; } public static void createFile(String fileName) throws Exception { Document document = DocumentHelper.createDocument(); Element root = document.addElement("students"); Element stuEle = root.addElement("student"); stuEle.addAttribute("id", "001"); Element nameEle = stuEle.addElement("name"); nameEle.setText("张三"); Element ageEle = stuEle.addElement("age"); ageEle.setText("20"); witerXMLFile(document,fileName) ; } public static void modifyFile(String fileName) throws Exception{ SAXReader sax = new SAXReader() ; Document document = sax.read(new File(fileName)) ; //修改 List<Attribute> list = document.selectNodes("students/student/@id") ; for(Attribute a :list){ if(a.getText().equals("001")){ a.setText("007") ; } } witerXMLFile(document,fileName) ; } public static void deleteFile(String fileName) throws Exception{ SAXReader sax = new SAXReader() ; Document document = sax.read(new File(fileName)) ; //删除节点 List<Element> list = document.selectNodes("students/student") ; for(Element e :list){ Attribute a = e.attribute(0) ; if(a.getText().equals("007")){ e.remove(a) ; } } witerXMLFile(document,fileName) ; } //写文件 public static void witerXMLFile(Document document,String fileName)throws Exception{ OutputFormat format = new OutputFormat(" ",true) ; format.setEncoding("GBK") ; XMLWriter w = new XMLWriter(new FileWriter(new File(fileName)),format) ; w.write(document) ; w.close() ; } }

<?xml version="1.0" encoding="GBK"?> <students> <student id="001"> <name>张三</name> <age>20</age> </student> </students>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值