dom4j簡單使用

2021-05-26 22:59:23 字數 1139 閱讀 3601

公司這邊是用dom4j,主要是用來解析xml的,一般有這麼幾個操作:

1.建立xml文件:

org.dom4j.document doc = documenthelper.createdocument();

2.建立根元素並新增:

element root = documenthelper.createelement("featurelist");

doc.add(root);

3.建立其他子元素並新增屬性:

element featureelement = documenthelper.createelement("feature");

新增子元素到根節點:

root.add(featureelement);

4.建立子元素的屬性並新增:

org.dom4j.attribute attr = attr = documenthelper.createattribute(featureelement, "fieldflag", offerfeature.getfieldflag());

featureelement.add(attr);

5.把內容格式化:(這個是直接關係到整個xml的格式,如編碼、元素間的內容)

/** 格式化輸出 */

outputformat format = outputformat.createprettyprint();

/** 指定xml編碼 */

format.setencoding("gbk");

stringwriter sw = new stringwriter();

xmlwriter xmlwriter = new xmlwriter(sw, format);

xmlwriter.write(doc);

xmlwriter.flush();

xmlwriter.close();

return sw.tostring();

當然要捕獲異常處理。

這也是儲存在offer表中最大欄位member_define_properties的操作情況。

幾個問題:

1.效率慢:全部載入完成後再進行解析

2.耗記憶體

3.如果xml是規範的形式,建議用邊解析邊載入的sax,當然目前已經有很多其他的解析工具。

dom4j 使用dom4j生成xml

使用org.dom4j.element 建立xml 生成service.xml檔案 param tran 交易物件 param filepath 資料夾路徑 public static void exportservicexml listtranlist,string filepath servic...

dom4j讀取XML簡單使用

測試例子1 suppresswarnings unchecked public class testdom4j 得到文件的document param is return throws documentexception public static document getdocument inpu...

dom4j使用總結

1.載入xml 從檔案載入 saxreader reader new saxreader string filepath xmlfile filename xml document document null try catch documentexception e return document...