java对象转xml_java对象和xml相互转换

Castor-xml.jar包

——Castor可以完成Java和XML的相互转换:

1)利用mapping配置,编组JavaObject、解组XML

在此之前我们设置过mapping.xml。如果不设置,肯定是不能转换成我们想要的XML的。那么,mapping.xml配置文件是怎么配置Account这个对象的呢

mapping.xml配置如下

2)转换实现工具类

import java.io.IOException;

import java.io.StringReader;

import java.io.StringWriter;

import org.exolab.castor.mapping.Mapping;

import org.exolab.castor.mapping.MappingException;

import org.exolab.castor.xml.MarshalException;

import org.exolab.castor.xml.Marshaller;

import org.exolab.castor.xml.Unmarshaller;

import org.exolab.castor.xml.ValidationException;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

import org.xml.sax.InputSource;

public class TranslateXmlTools {

public static String convertDTOtoXml(Object obj) throws Exception {

String returnstr = null;

try {

StringWriter sw = new StringWriter();

Mapping mapping = new Mapping();

Resource input = new ClassPathResource("castor-mapping-DTO.xml");

mapping.loadMapping(new InputSource(input.getInputStream()));

Marshaller unmar = new Marshaller(sw);

unmar.setMapping(mapping);

unmar.marshal(obj);

sw.flush();

returnstr = sw.toString();

} catch (Exception ex) {

ex.printStackTrace();

}

return returnstr;

}

public static Object convertXmltoDTO(String xmlStr) throws Exception {

if (null == xmlStr || "".equals(xmlStr)) {

throw new Exception("xml转dto报错,传入参数为空");

}

Mapping mapping = new Mapping();

Resource input = new ClassPathResource("castor-mapping-DTO.xml");

User user = null;

try {

mapping.loadMapping(new InputSource(input.getInputStream()));

Unmarshaller unmar = new Unmarshaller(User.class);

unmar.setMapping(mapping);

user = (User) unmar.unmarshal(new StringReader(xmlStr));

return user;

} catch (MarshalException ex) {

ex.printStackTrace();

} catch (ValidationException ex) {

ex.printStackTrace();

} catch (IOException ex) {

ex.printStackTrace();

} catch (MappingException ex) {

ex.printStackTrace();

} catch (Exception ex) {

ex.printStackTrace();

}

return user;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值