Posted on 2010-01-14 23:02
疯狂 阅读(2983)
评论(2) 编辑 收藏 所属分类:
java
使用freemarke输出xml:
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FrermarkerXml {
Template testfile;
Map root;
FrermarkerXml(){
init();
initData();
}
private void initData() {
root = new HashMap();
User user = new User();
user.setName("qiaobing11");
user.setPwd("password11");
List<Address> addresses = new ArrayList<Address>();
for (int i = 0; i < 10; i++) {
Address address = new Address();
address.setName("address_"+i);
addresses.add(address);
}
Map<String, Address> keyadds = new HashMap<String, Address>();
for (int i = 0; i < 10; i++) {
Address address = new Address();
address.setName("mapaddress_"+i);
keyadds.put("keyadd_"+i, address);
}
user.setAdds(addresses);
user.setKeyadds(keyadds);
root.put("user", user);
}
private void init(){
try {
Configuration tempConfiguration = new Configuration();
tempConfiguration.setClassicCompatible(true);
tempConfiguration.setClassForTemplateLoading(this.getClass(), "/config");
tempConfiguration.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
tempConfiguration.setNumberFormat("");
tempConfiguration.setDefaultEncoding("utf-8");
testfile = tempConfiguration.getTemplate("test.flt");
} catch (IOException ex) {
ex.printStackTrace();
}
}
public String toString(){
StringWriter sw = new StringWriter();
try {
testfile.process(root, sw);
} catch (Exception ex) {
ex.printStackTrace();
}
return sw.toString();
}
/**
* @param args
*
*/
public static void main(String[] args) {
System.out.println(new FrermarkerXml().toString());
}
}
user.java
import java.util.List;
import java.util.Map;
public class User {
private String name;
private String pwd;
private List<Address> adds;
private Map<String, Address> keyadds;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public List<Address> getAdds() {
return adds;
}
public void setAdds(List<Address> adds) {
this.adds = adds;
}
public Map<String, Address> getKeyadds() {
return keyadds;
}
public void setKeyadds(Map<String, Address> keyadds) {
this.keyadds = keyadds;
}
}
address.java
public class Address {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
test.flt
<用户名>${user.name}</用户名>
<密码>${user.pwd}</密码>
<#list user.adds as add>
<address>
<地址>List对象address值:${add.name} </地址>
</address>
</#list>
<#list user.keyadds?keys as addkey>
</address>
key:${addkey}
value:${user.keyadds[addkey].name}
</address>
</#list>