Apache Commons是Apache软件基金会的项目,曾隶属于Jakarta项目。Commons的目的是提供可重用的、开源的Java代码。Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。
Betwixt
本例主要介绍组件Betwixt,其功能是实现XML与Java对象之间相互转换(Turningbeans into XML)。
本例依赖的jar文件
/ApacheCommons/WebRoot/WEB-INF/lib/commons-beanutils-1.9.3.jar
/ApacheCommons/WebRoot/WEB-INF/lib/commons-betwixt-0.8.jar
/ApacheCommons/WebRoot/WEB-INF/lib/commons-collections-3.2.1.jar
/ApacheCommons/WebRoot/WEB-INF/lib/commons-digester-2.1.jar
/ApacheCommons/WebRoot/WEB-INF/lib/commons-lang-2.4.jar
/ApacheCommons/WebRoot/WEB-INF/lib/commons-logging-1.1.3.jar
本例演示简单Java对象与XML之间的相互转换。
1、创建简单Java对象
public class Person {
private String name;
private int age;
private boolean isAdult;
public Person() {}
public Person(String name, int age, boolean isAdult) {
this.name = name;
this.age = age;
this.isAdult = isAdult;
}
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;
}
/*boolean 类型的getter*/
public boolean getIsAdult() {
return isAdult;
}
/*boolean 类型的setter*/
public void setIsAdult(boolean isAdult) {
this.isAdult = isAdult;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", isAdult=" + isAdult
+ "]";
}
}
2、转换测试类
public class TestBetwixt {
public static void main(String[] args) throws Exception{
readXML2Bean();
writeBean2XML();
}
public static void readXML2Bean() throws Exception{
StringReader xmlReader = new StringReader("<?xml version='1.0' ?><person><isAdult>true</isAdult><name>James Smith</name><age>25</age></person>");
BeanReader beanReader = new BeanReader();
beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanReader.getBindingConfiguration().setMapIDs(false);
beanReader.getBindingConfiguration().setObjectStringConverter(new BooleanConverter());
beanReader.registerBeanClass("person", Person.class);
Person person = (Person) beanReader.parse(xmlReader);
System.out.println(person);
}
public static void writeBean2XML() throws Exception {
StringWriter stringWriter = new StringWriter();
// 写xml文件头
stringWriter.write("<?xml version='1.0' ?>"+"\n");
BeanWriter beanWriter = new BeanWriter(stringWriter);
IntrospectionConfiguration config = beanWriter.getXMLIntrospector().getConfiguration();
BindingConfiguration bc = beanWriter.getBindingConfiguration();
// bc.setObjectStringConverter(new DateConverter());
bc.setMapIDs(false);
config.setAttributesForPrimitives(false);
config.setAttributeNameMapper(new HyphenatedNameMapper());
config.setElementNameMapper(new DecapitalizeNameMapper());
beanWriter.enablePrettyPrint();
Person person = new Person("Jim", 12, true);
beanWriter.write(person.getClass().getSimpleName(), person);
beanWriter.close();
System.out.println(stringWriter.toString().trim());
}
}