一般来说,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());
明显,上述代码没有书写问题和节点关系问题,它的书写过程是逐渐深入子节点的,代码连贯性好多了,即使代码超过一屏也能有效控制.
以上.