一、通过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);
}
}
}