一般來說,Ajax程序中,ResponseXml輸出一般使用XML拼接,舉例如下:
PrintWriter out = response.getWriter();

out.println("<response>");
List<InOutType> types = service.search(predicate);
out.println("<status>passed</status>");
out.println("<message>查詢出的記錄數為:" + types.size() + "條</message>");

for (InOutType typeTmp : types)
{
out.println("<type>");
out.println("<name>" + typeTmp.getName() + "</name>");
out.println("</type>");
}
out.println("</response>");
個人認為這樣的方式用在小規模(編輯器一屏之內)ResponseXml還行,大規模就容易出錯了,它有以下缺點:
1.節點開始如<response>和節點結束</response>必須成對書寫,容易遺忘出錯.
2.節點和子節點關系不清晰.
我設想用dom4j來解決這個問題,具體就是把上述代碼中的XML轉化成一個Document的節點,這樣成對書寫問題和節點關系的問題都能解決了.
具體的類如下:
package com.sitinspring.nnyy.util;

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


public class XmlAssemble
{
private Document document;
private Element root;

public XmlAssemble(String rootName)
{
document=DocumentHelper.createDocument();
root = document.addElement(rootName);
}

public String getXml()
{
return document.asXML();
}

public Element add(String elmName)
{
return root.addElement(elmName);
}

public Element add(String elmName,String elmTxt)
{
Element elm=root.addElement(elmName);
elm.setText(elmTxt);
return elm;
}


public Element getRoot()
{
return root;
}
}
在這個類的幫助下,原有代碼改寫為:
List<InOutType> types = service.search(predicate);
XmlAssemble xmlAssemble=new XmlAssemble("response");
xmlAssemble.add("status","passed");
xmlAssemble.add("message","查詢出的記錄數為:"+ types.size() + "條");

for (InOutType typeTmp : types)
{
Element typeElm=xmlAssemble.add("type");
Element nameElm=typeElm.addElement("name");
nameElm.setText(typeTmp.getName());
}
PrintWriter out = response.getWriter();
out.println(xmlAssemble.getXml());
明顯,上述代碼沒有書寫問題和節點關系問題,它的書寫過程是逐漸深入子節點的,代碼連貫性好多了,即使代碼超過一屏也能有效控制.
以上.