用dom4j对xml进行创建、加载和更新

自:http://hi.baidu.com/waltertan/blog/item/3e705cc7085187d7d0006053.html

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


public class Dom4j_Test {

/**
* @param args
*/
//加载现有的xml文件到内存中
public void load(String paht){
   Document doc = null;
   Element root = null;
   List<Element> list = null;
   SAXReader reader = new SAXReader();
  
   try {
    doc = reader.read(new File(paht));
   } catch (DocumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  
   if(doc != null){
    root = doc.getRootElement();
    list = root.element("students").elements("student");
   
    for(Iterator<Element> it=list.iterator();it.hasNext();){
     Element element = it.next();
     System.out.print(element.attributeValue("id")+" "+element.elementText("name")+" ");
     System.out.println(element.elementText("gender"));
    }
   }
}

//创建一个xml的数据岛,并写进数据
public void create(String path){
   Document document = DocumentHelper.createDocument();
   Element root = document.addElement("root");
   Element elm = root.addElement("book");
   elm.addText("Java");
  
   root.addElement("book").addAttribute("id", "2").addText("C#");
  
   try {
    XMLWriter writer = new XMLWriter(new FileWriter(path));
    writer.write(document);
    writer.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
}

//更新现有的xml文件(以追加元素为例)
public void update(String path){
   SAXReader reader = new SAXReader();
   Document doc = null;
   try {
    doc = reader.read(new File(path));//将现有的xml文件读进内存
   } catch (DocumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  
//开始修改xml文件(在内存中修改)
   if(doc != null){
    Element elm = doc.getRootElement().element("students");
    Element elm2 = elm.addElement("student").addAttribute("id", "3");
    elm2.addElement("name").addText("Jennet");
    elm2.addElement("gender").addText("female");
   
   //将修改后的xml文件写到磁盘上
    try {
     XMLWriter writer = new XMLWriter(new FileWriter(path));
     writer.write(doc);
     writer.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
}

public static void main(String[] args) {
   // TODO Auto-generated method stub
   Dom4j_Test test = new Dom4j_Test();
  
   test.create("my2.xml");
   test.load("my1.xml");
   test.update("my1.xml");
}
}


你可能感兴趣的:(java,xml)