Digester解析xml的几种情况

前端之家收集整理的这篇文章主要介绍了Digester解析xml的几种情况前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在工作中,调用第三方接口时,会解析不同的xml格式,解析xml的方式有很多,但是Digester比较简单,以下是我遇到的几种情况:

第一种情况:input=

<channelid="1"code="AHTV1"name="安徽卫视"short_name="安徽卫视"country_code="CN" station_code="AHTV"/>

解析:Digester digester = new Digester();
digester.setValidating(false);
digester.push(this);
digester.addObjectCreate("document/Metainfo", channelInfo.class);//channelInfo.class是对应的实体类;

digester.addSetProperties("document/Metainfo","id","id");
digester.addSetProperties("document/Metainfo","name","name");

digester.addSetNext("document/channel","addChannelInfo");//addChannelInfo是下面一个方法,将对象放到一个集合中;


digester.parse(new ByteArrayInputStream(input.getBytes()));


public void addChannelInfo(TvMaoChannelInfo channelInfo) {
channelInfos.add(channelInfo);
}


第二种情况:input=

<document><Metainfo><id>ec19cb38f57fb3a0</id><name>旋转的爱</name></Metainfo></document>

解析:Digester digester = new Digester();
digester.addObjectCreate("document/Metainfo",ColumnMetaInfo.class);
digester.addBeanPropertySetter("document/Metainfo/id","id");
digester.addBeanPropertySetter("document/Metainfo/name","name");

ColumnMetaInfo columnMetaInfo = (ColumnMetaInfo) digester.parse(new ByteArrayInputStream(input.getBytes()));



第三种情况:接受的xml中,第二种情况中,包含集合的:

Digester digester = new Digester();

digester.addObjectCreate("document",DramaInfo.class);//实体类
digester.addObjectCreate("document/Metainfo",DramaMetainInfo.class);//实体类


digester.addBeanPropertySetter("document/Metainfo/id","name")
digester.addSetNext("document/Metainfo","setDramaMetainInfo");//将DramaMetainInfo对象set到DramaInfo

digester.addObjectCreate("document/episodes/section",DramaSection.class);//实体类
digester.addSetProperties("document/episodes/section","number","number");
digester.addBeanPropertySetter("document/episodes/section","content");
digester.addSetNext("document/episodes/section","addEpisodes");//将DramaSection放到集合中,并将集合set到DramaInfo

digester.addObjectCreate("document/pictures/url",ImageInfo.class);//实体类
digester.addBeanPropertySetter("document/pictures/url","url");
digester.addSetNext("document/pictures/url","addImageInfo");/将ImageInfo放到集合中,并将集合set到DramaInfo

DramaInfo dramaInfo = (DramaInfo) digester.parse(new ByteArrayInputStream(input.getBytes()));

其中:DramaInfo.class中包含DramaMetainInfo属性DramaSection集合,ImageInfo集合

原文链接:https://www.f2er.com/xml/299804.html

猜你在找的XML相关文章