使用JAXB将Java对象转xml
1. 要求生成的xml
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<result status="success" msg="成功"/>
</root>
2. Java对象
RootVO.java
@Data
@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class RootVO {
@XmlElement(name = "result")
public ResultVO result;
@Data
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement(name = "result")
@XmlAccessorType(XmlAccessType.FIELD)
public static class ResultVO{
@XmlAttribute(name = "status")
public String status;
@XmlAttribute(name = "msg")
public String msg;
}
}
3. 封装的工具类
XmlUtil.java
public class XmlUtil {
public static String objToXml(Object obj) {
try {
//创建JAXB对象,用于映射java类和xml
JAXBContext context = JAXBContext.newInstance(obj.getClass());
//创建Marshaller对象,用于将java对象序列化为xml
Marshaller marshaller = context.createMarshaller();
//设置编码格式
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//格式化生成xml
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//将java对象序列化为xml
marshaller.marshal(obj, byteArrayOutputStream);
return byteArrayOutputStream.toString("UTF-8");
} catch (JAXBException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
4. 测试
public static void main(String[] args) {
RootVO rootVO = new RootVO();
RootVO.ResultVO resultVO = new RootVO.ResultVO("success","成功");
rootVO.setResult(resultVO);
String xmlContent = XmlUtil.objToXml(rootVO);
System.out.println(xmlContent);
}
输出结果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<result status="success" msg="成功"/>
</root>
取掉standalone
public static void main(String[] args) {
RootVO rootVO = new RootVO();
RootVO.ResultVO resultVO = new RootVO.ResultVO("success","成功");
rootVO.setResult(resultVO);
String xmlContent = XmlUtil.objToXml(rootVO);
System.out.println(xmlContent.replace("standalone=\"yes\"", ""));
}
输出结果:
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<result status="success" msg="成功"/>
</root>