用Apache Commons Betwixt 在XML与Java对象之间相互转换
项目地址:http://commons.apache.org/proper/commons-betwixt/
/**
* XML转Java
*/
public class ReadExampleApp {
public static final void main(String args[]) throws Exception {
//创建一个读取xml文件的流
StringReader xmlReader = new StringReader(
"<?xml version='1.0' ?><person><age>25</age><name>James Smith</name></person>");
//创建一个BeanReader实例,相当于转换器
BeanReader beanReader = new BeanReader();
//配置BeanReader实例
beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanReader.getBindingConfiguration().setMapIDs(false); //不自动生成ID
//注册要转换对象的类,并指定根节点名称
beanReader.registerBeanClass("person", PersonBean.class);
//将XML解析Java Object
PersonBean person = (PersonBean) beanReader.parse(xmlReader);
//在控制台输出对象
System.out.println(person);
}
}
/**
* 将java对象转换为xml,并输出到文件
*/
public class WriteExampleApp {
public static final void main(String [] args) throws Exception {
//创建一个输出流,将用来输出Java转换的XML文件
FileWriter outputWriter = new FileWriter("c:\\123.txt");
//输出XML的文件头
outputWriter.write("<?xml version='1.0' ?>");
//创建一个BeanWriter实例,并将BeanWriter的输出重定向到指定的输出流
BeanWriter beanWriter = new BeanWriter(outputWriter);
//配置BeanWriter对象
beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
beanWriter.enablePrettyPrint();
Person person = new Person("XXX", 21);
beanWriter.write(person);
//关闭输出流
outputWriter.close();
}
}
/**
* 将Java对象转换为XML,并获取其字符串
*
*/
public class WriteStringExampleApp {
public static final void main(String [] args) throws Exception {
String reslutXml;
//创建一个输出流,将用来输出Java转换的XML文件
StringWriter outputWriter = new StringWriter();
//输出XML的文件头
outputWriter.write("<?xml version='1.0' ?>");
//创建一个BeanWriter实例,并将BeanWriter的输出重定向到指定的输出流
BeanWriter beanWriter = new BeanWriter(outputWriter);
//配置BeanWriter对象
beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
beanWriter.enablePrettyPrint();
Person person = new Person("xxx", 21);
beanWriter.write(person);
reslutXml = outputWriter.toString();
//关闭输出流
outputWriter.close();
//控制台输出转换结果的字符串
System.out.println(reslutXml);
}
}