1、依赖包
<dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.10</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.59</version> </dependency>
2、解析xml内容
<xml> <head> <token>1234</token> </head> <body> <userInfo> <name>admin</name> <password>123456</password> <email>123@qq.com</email> </userInfo> </body> </xml>
3、工具类
@Slf4j public class XmlParseUtil { /** * 解析XMl内容,转换为POJO类 * * @param clazz 要解析的对象 * @param xml 解析的xml字符串 * @return 解析完成的对象 */ public static Object convertXmlStrToObject(Class clazz, String xml) { Object xmlObject = null; try { JAXBContext context = JAXBContext.newInstance(clazz); // 进行将Xml转成对象的核心接口 Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader sr = new StringReader(xml); xmlObject = unmarshaller.unmarshal(sr); } catch (Exception e) { log.error("convert xmlStr to object error, msg <{}>",e.getMessage(),e); } return xmlObject; } }
4、新建pojo
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(propOrder = {"head","body" }) // 子节点名称 @XmlRootElement(name = "xml") // 当前节点名称 @Data public class XmlRemoteDto { // 接收head标签 private Head head; // 接收body标签 private Body body; } @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "body") @XmlType(name = "userInfo") @Data public class Body { @XmlElement(name = "userInfo") private UserInfo userInfo; } @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "head") // 当前节点名称 @Data public class Head { @XmlElement(name = "token") // 子节点名称 private String token; } // 业务所需的参数封装类 @Data @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "userInfo") public class UserInfo { @XmlElement(name = "name") private String name; @XmlElement(name = "password") private String password; @XmlElement(name = "email") private String email; }
5、解析操作
XmlRemoteDto xmlRemoteDto = (XmlRemoteDto) XmlParseUtil.convertXmlStrToObject(XmlRemoteDto.class, paramXml); Body body = xmlRemoteDto.getBody();
标签:xml,name,class,private,xstream,解析,public From: https://www.cnblogs.com/niun/p/16785749.html