以前解析xml都是使用的w3c的一套api,今天嘗試了一下dom4j,覺得還是比較好用的。下面簡單介紹一下。
dom4j的官方網站是www.dom4j.org,你可以在http://www.dom4j.org/guide.html上找到簡單的使用範例。
今天使用時碰到的問題是要在輸出文件時在xml declaration中加入standalone=‘yes’這個屬性,如果使用w3c的api,則只需要以下的代碼:
/**
* Saves the dom tree to file.
*/
public void saveDocument() throws Exception {
File f = new File(outputFile);
Document doc;
doc = this.buildDocument();
Transformer t = TransformerFactory.newInstance().newTransformer();
// set the property
t.setOutputProperty(OutputKeys.VERSION, "1.0");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.setOutputProperty(OutputKeys.STANDALONE, "yes");
t.transform(new DOMSource(doc), new StreamResult(
new FileOutputStream(f)));
}
但是使用dom4j時找了很久也沒找到設置什麼屬性可以添加xml declaration中的屬性,後來在查了一些資料後發現,必須自定義一個XMLWriter
代碼如下:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/**
* use to change the xml declararion
* @author yiqian
*
*/
public class MyXMLWriter extends XMLWriter {
public MyXMLWriter(FileOutputStream fileOutputStream, OutputFormat format) throws UnsupportedEncodingException {
// TODO Auto-generated constructor stub
super(fileOutputStream,format);
}
@Override
protected void writeDeclaration() throws IOException {
OutputFormat format = getOutputFormat();
String encoding = format.getEncoding();
if (!format.isSuppressDeclaration()) {
if (encoding.equals("UTF8")) {
writer.write("<?xml version=/"1.0/"");
if (!format.isOmitEncoding()) {
writer.write(" encoding=/"UTF-8/"");
}
writer.write(" standalone=/"true/"");
writer.write("?>");
} else {
writer.write("<?xml version=/"1.0/"");
if (!format.isOmitEncoding()) {
writer.write(" encoding=/"" + encoding + "/"");
}
writer.write(" standalone=/"yes/"");
writer.write("?>");
}
if (format.isNewLineAfterDeclaration()) {
println();
}
}
}
這樣相對應的代碼就是:
/**
* Saves the dom tree to file.
*/
public void saveDocument() throws Exception {
File f = new File(outputFile);
Document doc;
doc = this.buildDocument();
OutputFormat format = new OutputFormat(" ", true);
XMLWriter writer = new MyXMLWriter(new FileOutputStream(f), format);
writer.write(doc);
writer.close();
}