传入参数为sql.
返回值为 流,或者文件格式.
jt 为spring自带.当然可以写成自己的.
/*
* list TO xml
* @another juzhi
*/
public String ListToXml(String sql){
Element root = new Element("root");
Document doc = new Document(root);
try {
List list = jt.queryForList(sql);
int lengLi = list.size();
for(int i =0 ;i<lengLi ;i++){
Element elements = new Element("item");
Map m = (Map)list.get(i);
Iterator it= m.keySet().iterator();
while (it.hasNext())
{
Object key=it.next();
String columName = key.toString();
String columValu = m.get(columName).toString();
elements.setAttribute(columName.toLowerCase(), columValu);
}
root.addContent(elements);
}
} catch (DataAccessException e) {
e.printStackTrace();
}
Format format = Format.getCompactFormat();
format.setEncoding("GBK");
format.setIndent(" "); //设置缩进
XMLOutputter xmlout = new XMLOutputter(format);
//FileOutputStream fo=new FileOutputStream("ccccccc.xml"); //文件输出方式
//xmlout.output(Doc, fo);
String reS = xmlout.outputString(doc).toString(); //流输出方式
return reS;
}
在Action 这样输出
//查询单个学生信息
public ActionForward getQueryStuInfo(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response){
response.setContentType("text/xml;charset=GBK");
response.setDateHeader("expires", 0);
String xmlStr = XXXXXX.ListToXml("sql");
try {
response.getWriter().print(xmlStr);
} catch (IOException ex) {
}
return null;
}
jsp 页面调用
$.ajax({
dataType : 'xml',
url:'<%=request.getContextPath()%>/creditmng.do',
data:'method=getQueryStuInfo&unm='+unm+'&udm='+udm+'&cid='+cid+'&ced='+ced,
success:function(xml){
$('#tabl_qinfo').empty(); //清空
$('#tabl_qinfo').append('<tr><td>学籍号</td><td>学生姓名</td></tr>');
$(xml).find('item').each(function(){
var userdm = $(this).attr('stu_dm');
var realname = $(this).attr('realname');
$('#tabl_qinfo').append('<tr><td>'+userdm+'</td><td>'+realname+'</td</tr>');
});
}
});