java marshaller_Marshaller类型中的marshal(Object,Result)方法不适用于参数(T,File)

我遵循http://www.mkyong.com/java/jaxb-hello-world-example/

文件或(结果)文件得到错误java.io.File不能转换为javax.xml.transform.Result

什么是正确的文字?

File file = new File(path);

JAXBContext jaxbContext = JAXBContext.newInstance(typeParameterClass.getClass());

Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

//output pretty printed

jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(boject, file);堆栈跟踪

java.lang.ClassCastException: java.io.File cannot be cast to javax.xml.transform.Result

at martin.XMLObj.ConvertObjectToXML(XMLObj.java:26)

at martin.Helloworld.main(Helloworld.java:100)原始代码

Customer customer = new Customer();

customer.setId(100);

customer.setName("mkyong");

customer.setAge(29);

XMLObj XMLtool = new XMLObj(Customer.class);

try {

XMLtool.ConvertObjectToXML("c:\\file5.xml", customer);

}

catch(Exception ex)

{

ex.printStackTrace();

}。

public class XMLObj {

final Class typeParameterClass;

public XMLObj(Class typeParameterClass) {

this.typeParameterClass = typeParameterClass;

}

public void ConvertObjectToXML(String path, T boject)

{

try {

File file = new File(path);

JAXBContext jaxbContext = JAXBContext.newInstance(typeParameterClass.getClass());

Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

//output pretty printed

jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

FileOutputStream fs = new FileOutputStream(file);

jaxbMarshaller.marshal(boject, fs);

fs.flush();

fs.close();

//jaxbMarshaller.marshal(boject, System.out);

} catch (JAXBException e) {

//e.printStackTrace();

Logger.getInstance().process_message(e.getMessage());

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

Logger.getInstance().process_message(e.getMessage());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public T ConvertXMLToObject(String path)

{

//Convert XML to Object

try {

File file = new File(path);

if(file.exists())

{

JAXBContext jaxbContext;

jaxbContext = JAXBContext.newInstance(typeParameterClass.getClass());

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

T bobj = (T) jaxbUnmarshaller.unmarshal(file);

System.out.println(bobj);

return bobj;

}

else

Logger.getInstance().process_message("File not exist in ConvertObjectToXML");

} catch (JAXBException e) {

// TODO Auto-generated catch block

Logger.getInstance().process_message(e.getMessage());

}

return null;

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值