java使用commons-betwixt 实现bean与xml互转(一)

2014-11-24 10:36:15 · 作者: · 浏览: 4

项目所需的jar包:


一、XML2BeanUtils.java工具类如下:

[java]
package com.aimilin;

import java.beans.IntrospectionException;

/**
* Xml文件与javaBean对象互转工具类
* @author LiuJunGuang
* @date 2012-11-21下午1:38:56
*/
public class XML2BeanUtils {
private static final String xmlHead = "< xml version='1.0' >\r\n";

/**
* 将javaBean对象转换成xml文件
* @author LiuJunGuang
* @param obj 待转换的javabean对象
* @return String 转换后的xml 字符串
* @throws IntrospectionException
* @throws SAXException
* @throws IOException
* @date 2012-11-21下午1:38:53
*/
public static String bean2XmlString(Object obj) throws IOException, SAXException, IntrospectionException {
if (obj == null)
throw new IllegalArgumentException("给定的参数不能为null!");
StringWriter sw = new StringWriter();
sw.write(xmlHead);//写xml文件头
BeanWriter writer = new BeanWriter(sw);
IntrospectionConfiguration config = writer.getXMLIntrospector().getConfiguration();
writer.getBindingConfiguration().setMapIDs(false);
config.setAttributesForPrimitives(false);
config.setAttributeNameMapper(new HyphenatedNameMapper());
config.setElementNameMapper(new DecapitalizeNameMapper());
writer.enablePrettyPrint();
writer.write(obj.getClass().getSimpleName(), obj);
writer.close();
return sw.toString();
}

/**
* 将xml文件转换成相应的javabean对象,对于List,Map,Array转换时需要在需要保证Bean类中有单个添加方法

*


* 例如:List<{@link String}> userNameList --> addUserNameList(String username)
* String[] items --> addItems(String item)
* Map userMap --> addUserMap(String key,User user)
*


* 注意:

* 目前还没有找到好的方法解决Map与Map嵌套,List与List等嵌套的问题,使用时应当避免以上几种情况。
* @author LiuJunGuang
* @param beanClass 待转换的javabean字节码
* @param xmlFile xml文件字符串
* @return 转换后的对象
* @throws IntrospectionException
* @throws SAXException
* @throws IOException
* @date 2012-11-21下午1:40:14
*/
@SuppressWarnings("unchecked")
public static T xmlSring2Bean(Class beanClass, String xmlFile) throws IntrospectionException, IOException,
SAXException {
if (beanClass == null || xmlFile == null || xmlFile.isEmpty())
throw new IllegalArgumentException("给定的参数不能为null!");
StringReader xmlReader = new StringReader(xmlFile);
BeanReader reader = new BeanReader();
reader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
reader.getBindingConfiguration().setMapIDs(false);
T obj = null;
reader.registerBeanClass(beanClass.getSimpleName(), beanClass);
obj = (T) reader.parse(xmlReader);
xmlReader.close();
return obj;
}
}

二、简单的javabean对象:
[java]
package com.aimilin;

public class PersonBean {

private String name;
private int age;

public PersonBean() {
}

public PersonBean(String name, int age) {
this.name = name;
this.age = age;
}

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;
}

@Override
pu