object转xml:
需要转换的object需要在类名上实现@XmlRootElement
解析的xml结构为
<类名>
<属性></属性>
....
</类名>
如果需要别名,可以@XmlRootElement(name="别名")
属性别名,在属性的get方法上加上@XmlElement(name="别名")
解析顺序默认按字母顺序,如果需要制定顺序
@XmlType(propOrder = {"属性1", "属性2",。。。})
使用XmlType时,如果有XmlElement,必须写上
包:import javax.xml.bind.*
实例(object转xml):
JAXBContext context = JAXBContext.newInstance(cls);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING,"utf-8");//编码格式
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);//是否省略xml头信息,默认false
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//是否格式化生成的xml串,默认false
Writer writer = new StringWriter();
marshaller.marshal(obj, writer);
实例(xml转object):
JAXBContext context = JAXBContext.newInstance(cls);//需要转换的类.calss
Unmarshaller unmarshaller = context.createUnmarshaller();
return unmarshaller.unmarshal(new StringReader(xml));//xml字符串