欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-16 12:34:19
...

可以将每层封装为类,然后使用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的根节点,花了两三个小时,汗颜!

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

相关标签: xml反序列化