自己原来写过一些,但用过的xstream和castor就摒弃山寨版本了,总体来说这两个都很方便,但各有千秋吧
需要转换的bean
castor版本
输出:
[quote]
2171
<?xml version="1.0" encoding="UTF-8"?>
<test-bean age="12"><address>114445</address><phone>12345678</phone><name>aaa</name></test-bean>
135
[/quote]
xstream版本:
输出:
[quote]
145
<bean>
<name>aaa</name>
<age>12</age>
<phone>12345678</phone>
<address>114445</address>
</bean>
103
[/quote]
稍微解释一下,同一个bean,xstream在转化效率上比castor高了一个数量级。
具体应用中就得看需求了,譬如现在项目需要为flex提供饼图所需要的数据,而flex的饼图组建不支持xstream这样的xml,而需要castor这般的格式,也就只能牺牲效率了。
附件为castoer和xstream的几个jar包,欢迎下载
需要转换的bean
public class TestBean {
String name;
int age;
String phone;
String address;
public TestBean(String name, int age, String phone, String address) {
this.name = name;
this.age = age;
this.phone = phone;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
castor版本
public class Bean2Xml {
public static void main(String[] args) throws MarshalException,
ValidationException {
TestBean tb = new TestBean("aaa", 12, "12345678", "114445");
long time = System.currentTimeMillis();
StringWriter sw = new StringWriter();
Marshaller.marshal(tb, sw);
System.out.println(System.currentTimeMillis() - time);
System.out.println(sw.toString());
System.out.println(sw.toString().length());
}
}
输出:
[quote]
2171
<?xml version="1.0" encoding="UTF-8"?>
<test-bean age="12"><address>114445</address><phone>12345678</phone><name>aaa</name></test-bean>
135
[/quote]
xstream版本:
public class Bean2XmlBeta {
public static void main(String[] args) {
TestBean tb = new TestBean("aaa", 12, "12345678", "114445");
long time = System.currentTimeMillis();
XStream xStream = new XStream();
xStream.alias("bean", TestBean.class);
String xml = xStream.toXML(tb);
System.out.println(System.currentTimeMillis() - time);
System.out.println(xml);
System.out.println(xml.length());
}
}
输出:
[quote]
145
<bean>
<name>aaa</name>
<age>12</age>
<phone>12345678</phone>
<address>114445</address>
</bean>
103
[/quote]
稍微解释一下,同一个bean,xstream在转化效率上比castor高了一个数量级。
具体应用中就得看需求了,譬如现在项目需要为flex提供饼图所需要的数据,而flex的饼图组建不支持xstream这样的xml,而需要castor这般的格式,也就只能牺牲效率了。
附件为castoer和xstream的几个jar包,欢迎下载