使用apache.commons.betwixt實現XML與Java對象互轉 (二)

#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]]]
相關文章
相關標籤/搜索