引言
Dom4j是一组Xml操作的组件包,主要用来读写XmL文件。由于DOM4J性能优良,功能强大,且具有易用性,所以现在已被广泛的应用开来。
DOM4J下载地址http://sourceforge.net/
代码如下:
<p>package cn.wtu.dom4j; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator;</p><p>import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter;</p><p>public class Dom4jTest {</p><p> public static String fileName = "E:/a.xml"; public static void main(String[] args) { // create(); read(); }</p><p> /** * 利用dom4j读取xml文件 */ private static void read() { // TODO Auto-generated method stub File file = new File(fileName); SAXReader reader = new SAXReader(); //建立SAX解析器读取 Document document = null; try { document = reader.read(file); //读取文档 } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } Element root = document.getRootElement(); //取得根元素 Iterator iter = root.elementIterator(); while(iter.hasNext()){ Element linkman = (Element) iter.next(); System.out.println("name:"+linkman.elementText("name")); System.out.println("email:"+linkman.elementText("email")); } }</p><p> /** * 利用dom4j生成xml文件 */ private static void create() { Document doc = DocumentHelper.createDocument(); //创建文档 Element address = doc.addElement("address"); //定义根节点address Element link = address.addElement("linkman"); //定义address下的子节点linkman Element name = link.addElement("name"); //定义linkman下的子节点name Element email = link.addElement("email");// 定义linkman下的子节点 email name.setText("心情不开心敲敲代码"); //设置name节点的内容<name>心情不开心敲敲代码</name> email.setText("<a target=_blank href="mailto:[email protected]');//">[email protected]");//</a>设置email节点的内容<email>[email protected]</email> OutputFormat format = OutputFormat.createPrettyPrint(); //设置文档输出格式 format.setEncoding("UTF-8"); //指定文档的编码 try { //向文件输出XML文档 XMLWriter writer = new XMLWriter(new FileOutputStream( new File(fileName)),//指定文档的存储位置 format); writer.write(doc); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </p>