#1.说明 上一篇博文说明了如何 实现XML和Object的互相转换。java
可是遇到XML有子元素集合时,会出现转换以后的对象子结点为空的状况。 搜了一些资料,终于解决了
#2.代码演示说明apache
如下代码将演示如何把一个 Java对象转成XML,再把XML转换成对象
#3.新建两个对象ide
Department对象,有Employee的集合属性
package entity; import java.util.ArrayList; import java.util.List; public class Department { private String departmentName; private List<Employee> employeeList; /** * 必须有一个空的构造函数 */ public Department() { this.employeeList = new ArrayList<Employee>(); } /** * 这个方法必须有,不然属性集合不会转换成功 添加集合属性元素的方法,add后的单词必须决定了xml中元素的名字 * * @param employee */ public void addEmployee(Employee employee) { this.getEmployeeList().add(employee); } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public List<Employee> getEmployeeList() { return employeeList; } public void setEmployeeList(List<Employee> employeeList) { this.employeeList = employeeList; } public Department(String departmentName, List<Employee> employeeList) { super(); this.departmentName = departmentName; this.employeeList = employeeList; } @Override public String toString() { return "Department [departmentName=" + departmentName + ", employeeList=" + employeeList + "]"; } }
package entity; public class Employee { private String employeeName; public Employee() { } public Employee(String employeeName) { super(); this.employeeName = employeeName; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } @Override public String toString() { return "Employee [employeeName=" + employeeName + "]"; } }
#4.对象与XML转换工具类函数
package com.icim.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import org.apache.commons.betwixt.io.BeanReader; import org.apache.commons.betwixt.io.BeanWriter; import org.apache.log4j.Logger; import entity.Department; public class XmlParseUtil { private static final Logger logger = Logger.getLogger(XmlParseUtil.class); private static final String XML_ROOT_NODE_NAME = "TRANSACTION"; public static final String XML_HEADER = "<?xml version='1.0' encoding='UTF-8' ?>"; /** * 将XML字符串 转换成 对象 * @param strInMsg : XML内容 * @param clazz * @return */ public static Object xml2Obj(String strInMsg, @SuppressWarnings("rawtypes") Class clazz) { BeanReader beanReader = new BeanReader(); Object parse = null; StringReader xmlReader = new StringReader(strInMsg); beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false); beanReader.getBindingConfiguration().setMapIDs(false); try { beanReader.registerBeanClass(XML_ROOT_NODE_NAME, clazz); parse = beanReader.parse(xmlReader); } catch (Exception ex) { logger.error(ex.toString()); } return parse; } /** * 将 对象 转换成 XML字符串 * @param inObj * @return */ public static String obj2Xml(Object inObj) { StringWriter sw = new StringWriter(); BeanWriter beanWriter = new BeanWriter(sw); sw.write(XML_HEADER); try { beanWriter.setEndOfLine(""); beanWriter.getBindingConfiguration().setMapIDs(false); beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false); beanWriter.setWriteEmptyElements(true); //输出空元素 beanWriter.write(XML_ROOT_NODE_NAME, inObj); } catch (Exception e) { logger.error(e.toString()); } return sw.toString(); } /** * 将XML文件转换成 对象 * @param fileName * @param clazz * @return */ public static Object file2Object(String fileName, Class clazz) { String fileContent = file2String(fileName); return xml2Obj(fileContent, clazz); } /** * 将XML文件转换成 对象 * @param fileName * @param clazz * @return */ public static Object file2Object(File file, Class clazz) { String fileContent = file2tring(file); return xml2Obj(fileContent, clazz); } /** * 读取文件所有内容 * @param fileName * @return */ private static String file2String(String fileName) { File file = new File(fileName); return file2tring(file); } /** * 读取文件所有内容 * @param file * @return */ private static String file2tring(File file) { String encoding = "ISO-8859-1"; Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { return new String(filecontent, encoding); } catch (UnsupportedEncodingException e) { System.err.println("The OS does not support " + encoding); e.printStackTrace(); return null; } } }
#5.测试类工具
import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.icim.util.XmlParseUtil; import entity.Employee; import entity.Department; public class XmlParseTest { @Test public void testXML() { List<Employee> employeeList = new ArrayList<Employee>(); employeeList.add(new Employee("xiaoming1")); employeeList.add(new Employee("xiaoming2")); Department department = new Department("it", employeeList); String xmlString = XmlParseUtil.obj2Xml(department); System.out.println(xmlString); Department obj2 = (Department) new XmlParseUtil().xml2Obj(xmlString, Department.class); System.out.println(obj2); } }
#6.执行结果 :测试
<?xml version='1.0' encoding='UTF-8' ?><TRANSACTION><departmentName>it</departmentName><employeeList><employee><employeeName>xiaoming1</employeeName></employee><employee><employeeName>xiaoming2</employeeName></employee></employeeList></TRANSACTION> Department [departmentName=it, employeeList=[Employee [employeeName=xiaoming1], Employee [employeeName=xiaoming2]]]