xml 与dto的相互转换

前端之家收集整理的这篇文章主要介绍了xml 与dto的相互转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

import org.exolab.castor.mapping.Mapping;

import org.exolab.castor.xml.Marshaller;

import org.exolab.castor.xml.Unmarshaller;

import org.w3c.dom.Document;

import org.xml.sax.InputSource;

1)

public class JasperReportUtil {

/**

* 将DTO转换成XML数据

* @param obj DTO对象

* @param encoding编码格式

* @return xml字符串

*/

public static String convertDTOtoXML(Object obj,String encoding) {

Mapping mapping = new Mapping();

try {

InputStream mappingFileIn = PrintContractDto.class.getClassLoader().getResourceAsStream("print/dto/PrintContract.xml");

mapping.loadMapping(new InputSource(mappingFileIn));

//1)dto转换成xml

StringWriter sw = new StringWriter();

long startTime = System.currentTimeMillis();

Marshaller marshaller = new Marshaller(sw);

marshaller.setMapping(mapping);

marshaller.setEncoding(encoding);

marshaller.marshal(obj);

sw.flush();

long endTime = System.currentTimeMillis();

System.out.println("DTO装化为XML用时:" + (endTime - startTime) + " ms");

//2xml文件转换成dto

Unmarshaller unmarshaller = new Unmarshaller(mapping);

PrintContractDto stuDist = (PrintContractDto) unmarshaller.unmarshal(new StringReader(sw.toString()));

return sw.toString();


} catch (Exception ex) {

System.out.println("单证对象转化为xml数据出错");

}

return null;

}


}


2) 下面是对应的PrintContract.xml文件内容:


<!DOCTYPE mapping PUBLIC

"-//EXOLAB/Castor Object Mapping DTD Version 1.0//EN"

"http://castor.exolab.org/mapping.dtd">

<mapping>

<description>Used for com.siyuan.castor.Student</description>

<class name="print.dto.PrintContractDto" auto-complete="true">

<map-to xml="Contract"/>

<field name="riskGroup" type="print.dto.RiskGroup" get-method="getRiskGroup" set-method="setRiskGroup">

<bind-xml name="riskGroup2" node="element"/>

</field>

</class>

<class name="print.dto.RiskGroup" auto-complete="true">

<!-- 类中的集合修改字段对应的节点名称 -->

<field name="planInfoList"

collection="arraylist"

type="print.dto.PlanDto"

get-method="getPlanInfoList"

set-method="setPlanInfoList">

<bind-xml name="planInfoList2" node="element"/>

</field>

</class>

</mapping>



3) http://orange5458.iteye.com/blog/1139596

猜你在找的XML相关文章