dao4j操作xml文件

 dom4j读取xml文件内容

import java.io.File;

import java.util.Iterator;

import java.util.List;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

/**

 * 利用dom4j读取xml文件内容

 * @author 王强松

 * @time 2012-4-22

 *

 */

public class Dom4jReader {

 

public static void main(String[] args) throws Exception {

SAXReader read = new SAXReader(); //获得SAX解析

File file = new File("D:"+File.separator+"address.xml");//文件对象

Document doc = read.read(file);//找到文本对象

Element address = doc.getRootElement();//找到根节点

Iterator iter = address.elementIterator();//取得全部子节点

while(iter.hasNext()){

Element linkman = (Element) iter.next();//取得一个linkman

String name = linkman.elementText("name");//取得元素name的text

String id = linkman.element("name").attributeValue("id");//取得元素name的id属性

String email = linkman.elementText("email");//取得元素email的text

System.out.println(name);

System.out.println(id);

System.out.println(email);

}

}

 

}

dom4j生成xml文件
import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
 
 
/**
 * dom4j生成xml文件
 * @author Administrator
 *
 */
public class Dom4jWrite {
 
public static void main(String[] args) throws Exception {
Document doc  = DocumentHelper.createDocument();//创建文件
Element addresslist = doc.addElement("addresslist");//定义节点
Element linkman = addresslist.addElement("linkman");
Element name = linkman.addElement("name");
name.addAttribute("id", "0001");
Element email = linkman.addElement("email");
name.setText("Alex");
email.setText("[email protected]");
OutputFormat format = OutputFormat.createPrettyPrint();//设置输出格式
format.setEncoding("GBK");
XMLWriter write = new XMLWriter(new FileOutputStream(new File("D:"+File.separator+"addresslist.xml")));
write.write(doc);
write.close();
}
 
}
 

你可能感兴趣的:(dom4j)