下载的地址为:http://www.dom4j.org/dom4j-1.6.1/
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; //================================================= //File Name : DOM4JWriter //------------------------------------------------------------------------------ //Author : Common //主类 //Function : DOM4JWriter public class DOM4JWriter { public static void main(String[] args) { // TODO 自动生成的方法存根 Document doc = DocumentHelper.createDocument(); //创建文档 Element addresslist = doc.addElement("addresslist"); //定义节点 Element linkman = addresslist.addElement("linkman"); //定义子节点 Element name = addresslist.addElement("name"); //定义子节点 Element email = addresslist.addElement("email"); //定义子节点 name.setText("张三"); //设置name节点内容 email.setText("www.baidu.com"); //设置email节点内容 //设置输出格式 OutputFormat format = OutputFormat.createPrettyPrint(); //设置输出编码 format.setEncoding("UTF-8"); try{ XMLWriter writer = new XMLWriter(new FileOutputStream(new File("/home/common/software/coding/HelloWord/JavaWeb/bin/name_out.xml")),format); writer.write(doc); //输出内容 writer.close(); //关闭输出流 }catch(IOException e){ e.printStackTrace(); } } }
解析输出文件
import java.io.File; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; //================================================= //File Name : DOM4JReader //------------------------------------------------------------------------------ //Author : Common //主类 //Function : DOM4JReader public class DOM4JReader { public static void main(String[] args) { // TODO 自动生成的方法存根 File file = new File("/home/common/software/coding/HelloWord/JavaWeb/bin/name_out.xml"); SAXReader reader = new SAXReader(); //建立SAX解析读取 Document doc = null; try{ doc = reader.read(file); //读取文档 }catch(DocumentException e){ e.printStackTrace(); } Element root = doc.getRootElement(); //取得根元素 Iterator iter = root.elementIterator(); //取得全部的子节点 while(iter.hasNext()){ Element linkman = (Element) iter.next(); //取得每一个linkman System.out.println("姓名:"+linkman.elementText("name")); System.out.println("邮件:"+linkman.elementText("email")); } } }