2010年1月3日 星期日

利用dom4j解構與解析XML(一)

利用dom4j可以進行XML的解析與建構,可到dom4J Sourceforge下載。

在建構的時候必須要先建構一個Document物件,然後再往下加Element物件,透過這種方式,一步步的將XML建構出來。

如下的程式碼:

package com;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class BuildTest {

/**
* @param args
*/
public static void main(String[] args)
{
// 創建須放在XML裏的範例
// TODO Auto-generated method stub
ProductCategory category1 = new ProductCategory();
category1.setProductCategoryId("0001");
category1.setCategoryName("小說");
category1.setCategoryLevel("B");
category1.setParentId("001");
category1.setCategoryDesc("電子書類別");
category1.setOrderBy("1");

ProductCategory category2 = new ProductCategory();
category2.setProductCategoryId("0002");
category2.setCategoryName("漫畫");
category2.setCategoryLevel("B");
category2.setParentId("002");
category2.setCategoryDesc("電子書類別");
category2.setOrderBy("1");

List list = new ArrayList ();

list.add(category1);
list.add(category2);

// 呼叫buildeXML(...)
BuildTest test = new BuildTest();
System.out.println(test.buildXML(list));

}

public String buildXML(List list) {
Integer TotalRecordCount = list.size();

// 創建一個Document實例
Document document = DocumentHelper.createDocument();
// 生成Document下的一個根節點
Element root = document.addElement("Response");
// 生成root的一個節點
Element apiName = root.addElement("BbPdtCategorySelRsp");
// 加入TotalRecordCount節點
Element count = apiName.addElement("TotalRecordCount");
// 設置TotalRecordCount節點的值
count.addText(TotalRecordCount.toString());
// 加入CategoryInfoList節點
Element categoryInfoList = apiName.addElement("CategoryInfoList");
// 加入多個CategoryInfoList節點
for (ProductCategory temp : list) {
Element categoryInfo = categoryInfoList.addElement("CategoryInfo");

Element categoryID = categoryInfo.addElement("CategoryID");
categoryID.addText(temp.getProductCategoryId() == null ? "" : temp
.getProductCategoryId().toString());
Element categoryName = categoryInfo.addElement("CategoryName");
categoryName.addText(temp.getCategoryName() == null ? "" : temp
.getCategoryName());
Element parentID = categoryInfo.addElement("ParentID");
parentID.addText(temp.getParentId() == null ? "" : temp
.getParentId().toString());
Element categoryDesc = categoryInfo.addElement("CategoryDesc");
categoryDesc.addText(temp.getCategoryDesc() == null ? "" : temp
.getCategoryDesc());
Element categoryLevel = categoryInfo.addElement("CategoryLevel");
categoryLevel.addText(temp.getCategoryLevel() == null ? "" : temp
.getCategoryLevel().toString());
Element orderBy = categoryInfo.addElement("OrderBy");
orderBy.addText(temp.getOrderBy() == null ? "" : temp.getOrderBy()
.toString());

}
//傳回建構過很的XML
return document.asXML();
}

}

1 則留言:

匿名 提到...

You may also want to look at vtd-xml, which is more advanced and powerful than JDOM and DOM4J

http://vtd-xml.sf.net