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

相关文章

引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满足人的生产生活需要而产生的。具体...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章...
http://blog.jobbole.com/79252/ 引言 NOKIA 有句著名的广告语:“科技以人为本”。任何技术都是为了满...
(点击上方公众号,可快速关注) 公众号:smart_android 作者:耿广龙|loonggg 点击“阅读原文”,可查看...
一、xml与xslt 相信所有人对xml都不陌生,其被广泛的应用于数据数据传输、保存与序列化中,是一种极为强...