日期:2014-05-20  浏览次数:20894 次

struts2 如何生存xml文件?
Struts2+Hibernate+Spring开发,Struts2的Action怎样输出一个xml文件,这个文件的内容组成是由数据库中的用户表中的相关字段构成,比如:
 <?xml version="1.0" encoding="big5" ?> 
- <data>
- <user>
  <name>cary</name> 
  <ip>192.168.1.1</ip> 
  <state>0</state> 
  </user>
- <user>
  <name>apple</name> 
  <ip>192.168.1.1</ip> 
  <state>0</state> 
  </user>
  </data>


------解决方案--------------------
你从action里面获取数据库的列表就好生成了,下面是一个demo可以参考一下

package com.myservlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class DataToXML {
YourService yourService=new YourService ();
private static Document document;
//private String filename="mydata.xml";
static{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
document = builder.newDocument();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
//生成xml列表
public void writeToXMLList(String name,String filename){
List list=yourService.getMessageByName(name);//查询出你需要的数据列表
Element root=document.createElement("data");
document.appendChild(root);
for(int i=0;i<list.size();i++){
YourDomain input=(YourDomain)list.get(i);

Element ele=document.createElement("user");

root.appendChild(ele);

Element id=document.createElement("name");
id.setTextContent(input.getName()+"");
ele.appendChild(id);

Element name1=document.createElement("ip");
name1.setTextContent(input.getIp());
ele.appendChild(name1);

Element lng=document.createElement("status");
status.setTextContent(input.getLng()+"");
ele.appendChild(status);

}
this.saveXML(filename);
}
private void saveXML(String filename){
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
StreamResult result = new StreamResult(pw);
transformer.transform(source, result);
} catch (TransformerException mye) {
mye.printStackTrace();
} catch (IOException exp) {
exp.printStackTrace();
}
}

}
------解决方案--------------------
我查了一下,希望对楼主有帮助:
struts的resultType可以返回XSL Result,可以看struts2自带的app中的showcase例子,这个例子比较简单