上一篇写了用JAXP开发包解析XML,这一篇写下用Dom4J开发包解析XML。
JAXP虽然是sun公司自己开发的解析XML开发包,但是现在主流使用的解析XML开发包都是Dom4J。
使用Dom4J需要导入其开发包,点击进入官方下载地址
在下载文件docs/index.html,这是Dom4J的说明文档,其中有快速介绍如何具体使用相关API和常见的方法指南。
自己简单操作了创建document、得到document、增删改的功能,具体代码如下:
package com.shenyoujun.Dom4J;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class PlayDom4J {
String FilePath;
//Dom4J自身可以创建文档;
public Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("Exam");
Element sudent = root.addElement("student").addAttribute("name",
"poker").addAttribute("location", "UK").addText(
"James Strachan");
Element sudent2 = root.addElement("student")
.addAttribute("name", "Bob").addAttribute("location", "US")
.addText("Bob McWhirter");
return document;
}
//将document写入XML
public void write(Document document, String FilePath) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileWriter(FilePath), format);
writer.write(document);
writer.close();
}
//得到ducument
public Document getDocument(String FilePath) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(FilePath);
return document;
}
//增加标签or属性
public void add(String FilePath) throws DocumentException, IOException{
Document document =getDocument(FilePath);
Element exam =document.getRootElement();
List list =exam.elements();
//List list =document.selectNodes("/Exam/*");
for(Object i:list){
System.out.println(((Element) i).getText());
}
Element student = DocumentHelper.createElement("student");
student.setText("Dashen2");
student.setAttributeValue("name", "shen");
list.add(student);
write(document,FilePath);
}
//删除标签
public void delete(String FilePath) throws DocumentException, IOException{
Document document =getDocument(FilePath);
Element student=document.getRootElement().element("student");
student.getParent().remove(student);
write(document,FilePath);
}
//修改标签
public void update(String FilePath) throws DocumentException, IOException{
Document document =getDocument(FilePath);
Element student=(Element) document.getRootElement().elements("student").get(1);
student.setText("sax");
write(document,FilePath);
}
}