一、通過Jaxb來做二者之間的轉換
1. 使用jaxb的工具,或者netbeans ide根據xml的xsd來產生JavaBean
2. 使用jaxb的API,來實現xml和JavaBean之間的切換
public class JaxbUtil {
/**
* 讀取xml文件,轉成JavaBean
*/
public static Object unmarshal(String packagename,String path){
try{
JAXBContext jc = JAXBContext.newInstance(packagename);
Unmarshaller u = jc.createUnmarshaller();
Object Object = (Object)u.unmarshal(new File(path));
return Object;
}catch(Exception e){
throw new RuntimeException(e);
}
}
/**
* 將JavaBean轉成Xml輸出
*/
public static void marshaller(Object obj,String packagename,String path){
try{
JAXBContext jc = JAXBContext.newInstance(packagename);
//用於輸出元素
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
FileOutputStream stream = new FileOutputStream(path);
marshaller.marshal(obj, stream);
}catch(Exception e){
throw new RuntimeException(e);
}
}
}