我遵循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;
}
}