DOM4J介绍
DOM4J是使用Java语言编写的,用于读写及操作XML的一套组件,DOM4J同时具有DOM修改文件的优点和SAX读取快速的优点。
DOM4J的使用
首先下载dom4j的JAR包,我用的版本是1.6.1,下载地址:http://download.csdn.net/detail/onroads/9721574
使用方法《使用JDOM操作XML》,链接:http://www.cnblogs.com/centor/p/6215082.html
另外,解压后用到dom4j01.6.1.jar文件,还有一个lib/jaxen-1.1-beta-6.jar文件,一般也需要引入,否则执行时可能抛出java.lang.NoClassDefFoundError:org/jaxen/JaxenException异常。DOM4J的主要接口如下:
使用DOM4J
生成xml例程:
package com.xml; import java.io.File;
import java.io.FileOutputStream; import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter; public class XMLtest { public static void main(String args[]) throws Exception { String[] names = {"鸣人","佐助","小樱"};
String[] emails = {"mingren@163.com","zuozhu@163.com","xiaoying@163.com"};
String[] ids ={"H1","H2","H3"}; Document doc = DocumentHelper.createDocument();
Element addresslist = doc.addElement("addresslist"); for (int i = 0; i < 3; i++) {
Element linkman = addresslist.addElement("linkman");
Element name = linkman.addElement("name");
Element email = linkman.addElement("email");
name.setText(names[i]);
email.setText(emails[i]);
name.setAttributeValue("id", ids[i]);
} OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
try {
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("D:"+File.separator+"person.xml"), format);
xmlWriter.write(doc);
xmlWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
生成的xml文件:
解析XML文件:
package com.xml; import java.io.File;
import java.util.Iterator; import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; public class XMLtest { public static void main(String args[]) throws Exception { File file = new File("D:"+File.separator+"person.xml");
SAXReader reader = new SAXReader();
Document doc = null;
try {
doc = reader.read(file); } catch (Exception e) {
e.printStackTrace();
} Element root = doc.getRootElement();
Iterator iterator = root.elementIterator();
while(iterator.hasNext()){
System.out.println("<linkman>");
Element linkman = (Element) iterator.next();
System.out.println(" <name id="+ linkman.element("name").attributeValue("id")+">"+linkman.elementText("name")+"</name>");
System.out.println(" <email>"+linkman.elementText("email")+"</email>");
System.out.println("</linkman>");
}
}
}
解析结果: