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

2014-11-24 10:36:15 · 作者: · 浏览: 2
blic String toString() {
return "PersonBean[name='" + name + "',age='" + age + "']";
}
}
[java]
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 hobbyList;
private Map 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();
}
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();
}
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 getHobbyList() {
return hobbyList;
}

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

public Map getPersonMap() {
return personMap;
}

public void setPersonMap(Map 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) + "]";
}

}

测试类:
[java]
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 PersonBe