实现IQProvider

要在Spark处理OpenFire发送过来的IQ,必须要实现一个针对该IQ的IQProvider。

public interface IQProvider { /** * Parse the IQ sub-document and create an IQ instance. Each IQ must have a * single child element. At the beginning of the method call, the xml parser * will be positioned at the opening tag of the IQ child element. At the end * of the method call, the parser <b>must</b> be positioned on the closing tag * of the child element. * * @param parser an XML parser. * @return a new IQ instance. * @throws Exception if an error occurs parsing the XML. */ public IQ parseIQ(XmlPullParser parser) throws Exception; }

接口org.jivesoftware.smack.provider.IQProvider 只有一个方法

public IQ parseIQ(XmlPullParser parser) throws Exception;

该方法把xml解析成IQ对象,实现该方法最重要的就是了解XmlPullParser 对象,详细的可以参考文档

http://www.xmlpull.org/v1/doc/api/org/xmlpull/v1/XmlPullParser.html

写个使用例子:

public IQ parseIQ(XmlPullParser parser) throws Exception { int eventType = parser.getEventType(); String tagName = ""; UploadAttachResultIQ iq = new UploadAttachResultIQ(); while (true) { if (eventType == XmlPullParser.START_TAG) { tagName = parser.getName(); Log.debug("解析xml头:"+parser.getText()+","+tagName); }else if(eventType == XmlPullParser.TEXT){ Log.debug("解析xml:"+parser.getText()+","+tagName); if (tagName.equals("uploadresult")) { Log.debug("=====@@##====="+parser.getText()); iq.setSuccess(Boolean.parseBoolean(parser.getText())); } }else if(eventType == XmlPullParser.END_TAG && parser.getName().equals("uploadresult")){ Log.debug("解析xml尾:"+parser.getText()+","+tagName); break; } eventType = parser.next(); } return iq; }

该实现解释的IQ如下:

<iq type="result" id="-3eff5dd9:126885b5304:-8000" to="small@gy-viking/spark"><uploadresult xmlns="http://www.gyoa.com/uploadattachresult">true</uploadresult></iq>

方法输出:

解析xml头:<uploadresult xmlns="http://www.gyoa.com/uploadattachresult">,uploadresult

解析xml:true,uploadresult

=====@@##=====true

解析xml尾:</uploadresult>,uploadresult

说明: 在进入while(true)循环之前parser指向标签uploadresult的开始位置即<uploadresult xmlns="http://www.gyoa.com/uploadattachresult">
在循环里不断调用next() 返回当前的状态,然后根据不同的状态解析标签的属性和内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值