Java对象和XML相互转换
实际测试环境为:java 8
/**
* 类说明:xml和对象的相互转换
* <p>类需加注解"@XmlRootElement()"</br>
* 类字段加注解"@XmlAttribute(required=false)"来不生成到Xml中
*/
public class XmlKit
{
/**
* xml转换为对象
*
* @param xml
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T toObject(String xml,Class<T> clazz)
{
try
{
JAXBContext context=JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller=context.createUnmarshaller();
StringReader sr=new StringReader(xml);
return (T)unmarshaller.unmarshal(sr);
}
catch(JAXBException e)
{
e.printStackTrace();
return null;
}
}
/**
* 对象转换为xml
*
* @param obj
* @return
*/
public static String toXml(Object obj)
{
try
{
JAXBContext context=JAXBContext.newInstance(obj.getClass());
Marshaller marshaller=context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
StringWriter sw=new StringWriter();
marshaller.marshal(obj,sw);
return sw.toString();
}
catch(JAXBException e)
{
e.printStackTrace();
return null;
}
}
}
网友评论