使用XStream将xml字符串(文件)反序列化为javaBean去掉最外层(或根节点)的一种方法

本文介绍了一种使用XStream库将XML数据转换为Java对象的方法,通过封装类并利用processAnnotations函数,实现了XML数据的逐层解析与Java对象的映射。代码示例展示了如何读取包含多层结构的XML数据,并将其转换为相应的Java对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以将每层封装为类,然后使用XStream的processAnnotations函数将xml从外到内每个类添加进去,processAnnotations函数的作用是

Process the annotations of the given type and configure the XStream. A call of this method will automatically turn the auto-detection mode for annotations off.

使用fromXML函数将xml字符串当作参数传入,强转为最外层xml对应的类即可。

挂一下代码:

public class MainTest {
   public static void main(String[] args) throws BitAnswerException, ParseException {
      String xml = "<?xml version='1.0' encoding='UTF-8'?><sessionInfo timeZone='+08:00'><features sn='AAAAAAAAAAAAAAAA'><feature id='1' name='DeveloperId'type='ro' value='100654' op='0' /><feature id='2' name='鎺堟潈鐐规�绘暟' type='ro' value='15000' op='0' /><feature id='3' name='宸叉秷鑰楁巿鏉冪偣' type='rw' value='2407' op='0' /><feature id='12' name='BitKey' type='ro' value='0' endDate='2019-12-31 23:59:59' op='0' /></features></sessionInfo>";

      XStream xStream = new XStream(new DomDriver());

      xStream.processAnnotations(SessionInfoXML.class);
      xStream.processAnnotations(FeatureInfoListXml.class);

      SessionInfoXML sessionInfoXML = (SessionInfoXML) xStream.fromXML(xml);

      FeatureInfoListXml featureInfoListXml = sessionInfoXML.getFeatures();

      List<FeatureInfoXml> featureInfoXmlList = featureInfoListXml.getFeatures();

      for (FeatureInfoXml featureInfoXml : featureInfoXmlList) {
         System.out.println(featureInfoXml.getId() + "---" + featureInfoXml.getEndDate());
      }
   }
}

代码仅供参考和查看思路。

之前试了好多种方式都没有去掉xml的根节点,花了两三个小时,汗颜!

当然,也可以使用其它方法,这只是其中之一。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值