要在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() 返回当前的状态,然后根据不同的状态解析标签的属性和内容