xstream 解析xml报文
一、xml一种格式的数据转换为对象
pom.xml引入
<!--javaBean和XML的双向转换--> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.10</version> </dependency>
xml文件模板
<?xml version="1.0" encoding="GBK"?> <MESSAGE> <MESSAGEHEAD> <MESSAGEID/> <SRC/> </MESSAGEHEAD> <MESSAGEBODY> <TRANLIST> <TRAN_DATE/> <TRAN_TIME/> </TRANLIST> </MESSAGEBODY> </MESSAGE>
后台需要创建
1、 总类Total
class Total private static final String headInfo = "<?xml version=\"1.0\" encoding=\"GBK\"?>"; @XStreamAlias("MESSAGEHEAD") private Head head; @XStreamAlias("MESSAGEBODY") private Body body;
// getter setter
2、头部信息Head
class Head @XStreamAlias("MESSAGEID") private String messageId; @XStreamAlias("SRC") private String src; // getter settter
3、Body,明细类集合
class Body @XStreamImplicit(itemFieldName = "TRANLIST") private List<Detail> detail;
4、Detail明细类
class Detail @XStreamConverter(value = XStreamDateConverter.class) @XStreamAsAttribute @XStreamAlias("TRAN_DATE") private Date tranDate; @XStreamAlias("TRAN_TIME") private String tranTime;
// getter setter
需要强调的是: String类型不需要转换,其他的类型都可以通过实现接口SingleValueConverter来实现转换格式,编写一个转换日期Date格式的转换,其他类似
public class XStreamDateConverter implements SingleValueConverter { private final String YMD = "yyyyMMdd"; SimpleDateFormat dateFormat = new SimpleDateFormat(YMD); @Override public String toString(Object o) { String result = null; if (o instanceof Date) { Date date = (Date) o; result = dateFormat.format(date); } return result; } @Override public Object fromString(String s) { Date date = null; if (s != null && !"".equals(s)) { try { date = dateFormat.parse(s); } catch (ParseException e) { e.printStackTrace(); } } return date; } @Override public boolean canConvert(Class aClass) { return Date.class == aClass; } }
基础工作已经完成,接下来就是将xml转换为对象实体
public static Total transXmlToObject(String xmlBody) { XStream xStream = new XStream(); xStream.alias("MESSAGE", Total.class); xStream.alias("MESSAGEHEAD", Head.class); xStream.alias("MESSAGEBODY", Body.class); xStream.alias("TRANLIST", Detail.class); xStream.processAnnotations(new Class[]{Total.class, Head.class, Body.class, Detail.class}); Object object = xStream.fromXML(xmlBody); Total data = (Total) object; return data; }