/**
* JavaBean--->xml
String result = null;
try{
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//标签允许自动换行 否则为一行的xml
marshaller.setProperty(Marshaller.JAXB_ENCODING,encoding);//xml编码格式
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
/**
* Xml--->JavaBean
* */
public static <T> T converyToJavaBean(String xml,Class<T> c){
T t = null;
try{
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T)unmarshaller.unmarshal(new StringReader(xml));
}catch(Exception e){
e.printStackTrace();
}
return t;
}
* JavaBean--->xml
* */
public static String convertTotXml(Object obj){ return convertToXml(obj,"utf-8");} // 解除警告
private static String convertToXml(Object obj, Object encoding) {String result = null;
try{
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//标签允许自动换行 否则为一行的xml
marshaller.setProperty(Marshaller.JAXB_ENCODING,encoding);//xml编码格式
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
/**
* Xml--->JavaBean
* */
public static <T> T converyToJavaBean(String xml,Class<T> c){
T t = null;
try{
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T)unmarshaller.unmarshal(new StringReader(xml));
}catch(Exception e){
e.printStackTrace();
}
return t;
}