`
JayWay_Chen
  • 浏览: 4468 次
社区版块
存档分类
最新评论

xml的解析总结

阅读更多
//推送图文消息
			String title="";
			ArrayList<TextAndPicContentVo> articles=new ArrayList();
			NewsVo news=new NewsVo();
			StringReader read = new StringReader(xml);
			  InputSource source = new InputSource(read);
			  SAXBuilder sb = new SAXBuilder();
			  Document doc = sb.build(source);
			  Element root = doc.getRootElement();//获取根节点也就<xml>
			  List<Element> nodes = root.getChildren();
		for(int i=0;i<nodes.size();i++){
			Element e=nodes.get(i);
			if("Articles".equals(e.getName())){//找到articles结点
				List<Element> newsinfo=e.getChildren();//得到articles下的子结点List
				for(Element t:newsinfo){
					List<Element> weixinInfos = t.getChildren();//得到item结点下的子元素list
					   Map<String, Object> map = new HashMap<String, Object>(); 
                                      //将元素name作为key,value作为map的value,方便根据标签名获取便签内容
					for(Element infos:weixinInfos){//item下的子元素封装进map
						map.put(infos.getName(), infos.getValue());
					}
				 TextAndPicContentVo article=new TextAndPicContentVo();
				 title=(String) map.get("Title");
				 article.setTitle(title);
			     article.setDescription((String)map.get("Description"));
			     article.setPicurl((String)map.get("Picurl"));
			     article.setUrl((String)map.get("Url"));
			     articles.add(article);
				}
				for(Openid openid:openidList){//封装,批量推送消息
					SendTextAndPicVo weixinVo=new SendTextAndPicVo();
									news.setArticles(articles);
									weixinVo.setMsgtype("news");
									weixinVo.setNews(news);
									weixinVo.setTouser(openid.getOpenid());
									returnInfo=weixinUtil.sendTextandPicMsg(weixinVo,access_token);
									}

 

前两周开发了微信公众好后台管理系统,自己负责是粉丝管理模块,一切还算顺利,在发送客服消息(图文消息)的时候要解析数据库表里内容,里面存储是xml格式的,然而请求微信图文发送api用到的请求json里title,url,picurl这些信息都在xml里,必须解析封装成一个发送对象(该对象仅用来转换成json请求)。特此记录下核心代码,感觉还有更好的方法。用的jdom解析

ps:xml代码。

<xml>
<MsgType><![CDATA[news]]></MsgType><ArticleCount>2</ArticleCount><Articles>
  <item>
    <Picurl><![CDATA[https://mp.weixin.qq.com/cgi-bin/getimgdata?token=424356498&amp;msgid=&amp;mode=large&amp;source=file&amp;fileId=10000029&amp;ow=-1]]></Picurl>
    <Title><![CDATA[图文消息标题1]]></Title>
    <Url><![CDATA[www.baidu.com]]></Url>
    <Description><![CDATA[图文消息描述1]]></Description>
  </item>
  <item>
    <Picurl><![CDATA[https://mp.weixin.qq.com/cgi-bin/getimgdata?token=424356498&amp;msgid=&amp;mode=large&amp;source=file&amp;fileId=10000029&amp;ow=-1]]></Picurl>
    <Title><![CDATA[图文消息标题2]]></Title>
    <Url><![CDATA[www.baidu.com2]]></Url>
    <Description><![CDATA[图文消息描述2]]></Description>
  </item>
</Articles>
</xml>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics