最近因工作需要,在研究将Collection 生成xml文件,发现XStream的真的很好用,无需任何配置就可以将
Collection类的内容序列化为XML,下面我就将我的心得和大家分享一下。
首先请下载XStream,目前最新版本是1.3.1,下载地址:http://xstream.codehaus.org/download.html
请将下载后的jar文件包含到你的工程中。
我的javabean内容如下:
package sq_returnclass;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("HisKsxx") //请注意这里是设置生成XML文件的二级根元素的别名。
public class HisKsxx implements java.io.Serializable {
private String ksdm;
private String ksmc;
private String pydm;
public HisKsxx(Long ksdm,String ksmc,String pydm){
this.ksdm=ksdm.toString();
this.ksmc=ksmc;
this.pydm=pydm;
}
public HisKsxx(String ksdm,String ksmc,String pydm){
this.ksdm=ksdm;
this.ksmc=ksmc;
this.pydm=pydm;
}
public HisKsxx(){
}
public String getKsmc() {
return ksmc;
}
public void setKsmc(String ksmc) {
this.ksmc = ksmc;
}
public String getPydm() {
return pydm;
}
public void setPydm(String pydm) {
this.pydm = pydm;
}
public String getKsdm() {
return ksdm;
}
public void setKsdm(String ksdm) {
this.ksdm = ksdm;
}
}
从数据库中查询数据并生成XML。
public String GetXml() {
Collection<HisKsxx> coll;
coll = getHibernateTemplate()
.find( "select new sq_returnclass.HisKsxx(ksdm,ksmc,pydm) from GyKsdm ");
XStream xstream = new XStream();
Annotations.configureAliases(xstream, HisKsxx.class);
String str;
str = xstream.toXML(coll);
System.out.println(str);
return str;
}
生成的xml内容如下:
<list> <HisKsxx> <ksdm>1</ksdm> <ksmc>门诊科室</ksmc> <pydm>1211</pydm> </HisKsxx> <HisKsxx> <ksdm>4</ksdm> <ksmc>病区科室</ksmc> <pydm>41</pydm> </HisKsxx> <HisKsxx> <ksdm>5</ksdm> <ksmc>医技科室</ksmc> <pydm>51</pydm> </HisKsxx> <HisKsxx> <ksdm>6</ksdm> <ksmc>行政科室</ksmc> <pydm>6</pydm> </HisKsxx> <HisKsxx> <ksdm>7</ksdm> <ksmc>后勤科室</ksmc> <pydm>7</pydm> </HisKsxx> <HisKsxx> <ksdm>102</ksdm> <ksmc>门诊科室</ksmc> <pydm>12</pydm> </HisKsxx> </list>
哈哈,完成了,简单吧。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/caok/archive/2009/01/09/3741132.aspx