项目所需的jar包:

java使用commons-betwixt 实现bean与xml互转_java

一、XML2BeanUtils.java工具类如下:

package com.viathink.core.utils;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import org.apache.commons.betwixt.BindingConfiguration;
import org.apache.commons.betwixt.IntrospectionConfiguration;
import org.apache.commons.betwixt.expression.Context;
import org.apache.commons.betwixt.io.BeanReader;
import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.commons.betwixt.strategy.DecapitalizeNameMapper;
import org.apache.commons.betwixt.strategy.DefaultObjectStringConverter;
import org.apache.commons.betwixt.strategy.HyphenatedNameMapper;
import org.xml.sax.SAXException;

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

	/**
	 * 将javaBean对象转换成xml文件,对于没有设置的属性将不会生成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();
		BindingConfiguration bc = writer.getBindingConfiguration();
		bc.setObjectStringConverter(new DateConverter());
		bc.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类中有单个添加方法</br>
	 * <p><blockquote><pre>
	 * 例如:List<{@link String}> userNameList --> addUserNameList(String username)
	 *      String[] items            --> addItems(String item)
	 *      Map<String,User> userMap               --> addUserMap(String key,User user)
	 * </pre></blockquote></p>
	 * 注意:<br>
	 *     目前还没有找到好的方法解决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> T xmlSring2Bean(Class<T> 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);
		BindingConfiguration bc = reader.getBindingConfiguration();
		bc.setObjectStringConverter(new DateConverter());
		bc.setMapIDs(false);
		T obj = null;
		reader.registerBeanClass(beanClass.getSimpleName(), beanClass);
		obj = (T) reader.parse(xmlReader);
		xmlReader.close();
		return obj;
	}

	/**
	 * 日期转换,主要是解决日期为null或者空字符串解析报错问题
	 * @author LiuJunGuang
	 * @date 2013年12月31日下午6:56:49
	 */
	private static class DateConverter extends DefaultObjectStringConverter {
		private static final long serialVersionUID = -197858851188189916L;

		@Override
		@SuppressWarnings("rawtypes")
		public String objectToString(Object object, Class type, String flavour, Context context) {
			return super.objectToString(object, type, flavour, context);
		}

		@Override
		@SuppressWarnings("rawtypes")
		public Object stringToObject(String string, Class type, String flavour, Context context) {
			if (string == null || "".equals(string))
				return null;
			return super.stringToObject(string, type, flavour, context);
		}

	}
}




    二、简单的javabean对象:

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
	public String toString() {
		return "PersonBean[name='" + name + "',age='" + age + "']";
	}
}
package com.aimilin;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class User implements Serializable {
	private static final long serialVersionUID = 1354973253595584043L;
	private String userName;
	private int age;
	private PersonBean person;
	private List<String> hobbyList;
	private Map<String, PersonBean> personMap;
	private String[] hobbyArray;

	/**
	 * 添加map类型属性的方法
	 * @param key
	 * @param person
	 * @date 2012-11-29下午1:01:06
	 */
	public void addPersonMap(String key, PersonBean person) {
		if (personMap == null) {
			personMap = new HashMap<String, PersonBean>();
		}
		personMap.put(key, person);
	}

	/**
	 * 添加list类型的方法
	 * @param hobby
	 * @date 2012-11-29下午1:01:07
	 */
	public void addHobbyList(String hobby) {
		if (hobbyList == null) {
			hobbyList = new LinkedList<String>();
		}
		hobbyList.add(hobby);
	}

	/**
	 * 添加数组类型的方法
	 * @param hobby
	 * @date 2012-11-29下午1:01:09
	 */
	public void addHobbyArray(String hobby) {
		hobbyArray = StringUtils.addStringToArray(hobbyArray, hobby);
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public User() {
		super();
	}

	public PersonBean getPerson() {
		return person;
	}

	public void setPerson(PersonBean person) {
		this.person = person;
	}

	public List<String> getHobbyList() {
		return hobbyList;
	}

	public void setHobbyList(List<String> hobbyList) {
		this.hobbyList = hobbyList;
	}

	public Map<String, PersonBean> getPersonMap() {
		return personMap;
	}

	public void setPersonMap(Map<String, PersonBean> personMap) {
		this.personMap = personMap;
	}

	public String[] getHobbyArray() {
		return hobbyArray;
	}

	public void setHobbyArray(String[] hobbyArray) {
		this.hobbyArray = hobbyArray;
	}

	@Override
	public String toString() {
		return "User [userName=" + userName + ", age=" + age + ", person=" + person + ", hobbyList=" + hobbyList
				+ ", personMap=" + personMap + ", hobbyArray=" + Arrays.toString(hobbyArray) + "]";
	}

}



测试类:

package com.aimilin;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class XML2BeanUtilsTest {
	@Test
	//测试简单属性
	public void testPsersonBean() throws Exception {
		String xmlString = XML2BeanUtils.bean2XmlString(createPerson());
		System.out.println(xmlString);
		PersonBean person = XML2BeanUtils.xmlSring2Bean(PersonBean.class, xmlString);
		System.out.println(person);
	}

	@Test
	//测试复杂属性
	public void testUser() throws Exception {
		String xmlString = XML2BeanUtils.bean2XmlString(createUser());
		System.out.println(xmlString);
		User user = XML2BeanUtils.xmlSring2Bean(User.class, xmlString);
		System.out.println(user);
	}

	public PersonBean createPerson() {
		return new PersonBean("name", 23);
	}

	//创建复杂的用户对象
	public User createUser() {
		User user = new User();
		user.setAge(18);
		user.setUserName("张三");
		user.setHobbyArray(new String[] { "篮球", "足球", "乒乓球", "羽毛球" });
		user.setHobbyList(Arrays.asList(new String[] { "游泳", "蛙游", "蝶泳", "自由泳", "狗刨" }));
		user.setPerson(createPerson());
		Map<String, PersonBean> personMap = new HashMap<String, PersonBean>();
		for (int i = 0; i < 5; i++) {
			personMap.put("person" + i, new PersonBean("person" + i, i));
		}
		user.setPersonMap(personMap);
		return user;
	}
}




结果:testPsersonBean运行结果:

<?xml version='1.0' ?>
  <PersonBean>
    <age>23</age>
    <name>name</name>
  </PersonBean>

PersonBean[name='name',age='23']

testUser运行结果:

<?xml version='1.0' ?>
  <User>
    <age>18</age>
    <hobbyArray>
      <hobbyArray>篮球</hobbyArray>
      <hobbyArray>足球</hobbyArray>
      <hobbyArray>乒乓球</hobbyArray>
      <hobbyArray>羽毛球</hobbyArray>
    </hobbyArray>
    <hobbyList>
      <hobbyList>游泳</hobbyList>
      <hobbyList>蛙游</hobbyList>
      <hobbyList>蝶泳</hobbyList>
      <hobbyList>自由泳</hobbyList>
      <hobbyList>狗刨</hobbyList>
    </hobbyList>
    <person>
      <age>23</age>
      <name>name</name>
    </person>
    <personMap>
      <entry>
        <key>person3</key>
        <value>
          <age>3</age>
          <name>person3</name>
        </value>
      </entry>
      <entry>
        <key>person4</key>
        <value>
          <age>4</age>
          <name>person4</name>
        </value>
      </entry>
      <entry>
        <key>person1</key>
        <value>
          <age>1</age>
          <name>person1</name>
        </value>
      </entry>
      <entry>
        <key>person2</key>
        <value>
          <age>2</age>
          <name>person2</name>
        </value>
      </entry>
      <entry>
        <key>person0</key>
        <value>
          <age>0</age>
          <name>person0</name>
        </value>
      </entry>
    </personMap>
    <userName>张三</userName>
  </User>




User [userName=张三, age=18, person=PersonBean[name='name',age='23'], hobbyList=[游泳, 蛙游, 蝶泳, 自由泳, 狗刨], personMap={person3=PersonBean[name='person3',age='3'], person4=PersonBean[name='person4',age='4'], person1=PersonBean[name='person1',age='1'], person2=PersonBean[name='person2',age='2'], person0=PersonBean[name='person0',age='0']}, hobbyArray=[篮球, 足球, 乒乓球, 羽毛球]]