DOM4J读写文件

//DOM4J:http://dom4j.sourceforge.net
package com;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;

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;

public class TestDOM4J {
public static void main(String[] args) {
  try {
   XMLWriter writer = null;
         SAXReader reader = new SAXReader();
         OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");// 设置XML文件的编码格式
         File file = new File("book.xml");
         if(file.exists()){
          Document document = reader.read(file); //读取XML文件,获得Document对象
          Element root = document.getRootElement();
          Iterator<Element> iterator=root.elementIterator("book");
          while(iterator.hasNext()){
           Element element = iterator.next();
           if(element.attributeValue("num").equals("0001")){
            //修改编号为0001数据
            element.element("isbn").setText("1234567");
            element.element("name").setText("C#");
            //root.remove(element);刪除节点
            //写入文件
            writer = new XMLWriter(new FileWriter(file),format);
               writer.write(document);
               writer.close();    
           }
          }
         }else{
          //新建book.xml并添加內容
          Document document = DocumentHelper.createDocument();
          Element root = document.addElement("books");//根节点
          //增加节点
          Element element = root.addElement("book");
          element.addAttribute("num", "0001");//增加属性
          Element element_isbn = element.addElement("isbn");//增加节点
          element_isbn.setText("7-111-19059-9");
          Element element_name = element.addElement("name");
          element_name.setText("JAVA");
          //写入文件
          writer = new XMLWriter(new FileWriter(file),format);
          writer.write(document);
          writer.close();
         }
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }    
}

}
//实例包含了XML文件的增删改

你可能感兴趣的:(DOM4J读写文件)