cn.opencodes.utils.XmlUtils Maven / Gradle / Ivy
The newest version!
package cn.opencodes.utils;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
* xml
* @author HJ
*/
public class XmlUtils {
/**
* @param object 对象
* @return 返回xmlStr
*/
public static String beanToXml(Object object){
try{
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(object.getClass());
Marshaller marshal = context.createMarshaller();
marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化输出
marshal.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 编码格式,默认为utf-8
marshal.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xml头信息
marshal.setProperty("jaxb.encoding", "UTF-8");
marshal.marshal(object,writer);
return new String(writer.getBuffer());
} catch (Exception e) {
e.printStackTrace(); return null;
}
}
/**
* xml转换成JavaBean
* @param xml
* @param c
*/
@SuppressWarnings("unchecked")
public static T xmlToBean(String xml, Class 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;
}
}