dom4j简介: dom4j是一个易于使用的,用于XML的开放源代码库,在Java平台上使用Java集合框架并完全支持DOM和SAX使用XPath和XSLT。
闲来无事,用dom4j写了一个解析xml和生成xml的demo
/**
* Dom4j创建及解析xml文件
* @author gaoq
* @date 2015-5-12 下午6:05:48
*/
package com.test.transport.service;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.dom4j.Attribute;
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;
public class XMLService {
public Document getDocument(){
Document doc = DocumentHelper.createDocument();
doc.addComment("这是一个简单的狗剩demo");
Element root = doc.addElement("Dogs");
Element d1 = root.addElement("dog");
d1.addAttribute("color", "yellow");
d1.addAttribute("height", "20");
Element d2 = root.addElement("dog");
d2.addAttribute("color", "red");
d2.addAttribute("height", "18");
return doc;
}
public void saveDocument(Document doc,String filepath){
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = null;
try {
writer = new XMLWriter(new FileWriter(new File(filepath)), format);
writer.write(doc);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
//生产xml文件
creatXML();
//解析xml文件
readXml();
}
public static void readXml(){
File file = new File("E:\\9tuo\\workspace\\test\\狗剩.xml");
SAXReader sax = new SAXReader();
Document doc = null;
try {
doc = sax.read(file);
List<Element> ele = doc.selectNodes("//Dogs/dog");
for (Element s : ele) {
List<Attribute> e = s.attributes();
for(Attribute el : e){
System.out.println(el.getText().trim()+"===="+el.getName());
}
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void creatXML() {
XMLService service = new XMLService();
Document doc = service.getDocument();
service.saveDocument(doc, "狗剩.xml");
}
}