android XmlPullParser的简单应用

来源:互联网 发布:网络金融销售 编辑:程序博客网 时间:2024/04/30 14:51
package lxy.litsoft;import java.io.IOException;import java.io.StringReader;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import org.xmlpull.v1.XmlPullParserFactory;import android.app.Activity;import android.os.Bundle;import android.util.Log;public class AppMain extends Activity{    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        try {testParser();} catch (XmlPullParserException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}    }        private void testParser()throws XmlPullParserException,IOException    {    /**XmlPullParserFactory: this class is used to create implementation of XML Pull Parser.**/    //XmlPullParserFactory这个类用于实现一个XML的解析器    /**newInstance(): Create a new instance of a PullParserFactory that can be used to create XML pull parsers .**/    //newInstance()方法用于实例化一个PullParserFactory对象,以便于创建XML解析器    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();        /**setNamespaceAware():Specifies that the parser produced by this factory will provide support for XML names paces.**/    //指定由XmlPullParserFactory对象产生的解析器能提供对XML命名空间的支持        factory.setNamespaceAware(true);            /**Creates a new instance of a XML Pull Parser using the currently configured factory features.**/    //用当前的XmlPullParserFactory实例化一个XmlPullParser对象        XmlPullParser xpp = factory.newPullParser();        /**Set the input source for parser to the given reader and resets the parser.**/        //为解析器输入源,源为一个StringReader对象        /**StringReader:A specialized Reader that reads characters from a String in a sequential manner. **/        //StringReader类是一个专门的阅读器,以顺序的方式从字符串里读取字符        xpp.setInput( new StringReader ( "<liu>I am Liuliu</liu><huo>Missing Huohuo</huo>" ) );                /**Returns the type of the current event (START_TAG, END_TAG, TEXT, etc.)**/        int eventType = xpp.getEventType();        while (eventType != XmlPullParser.END_DOCUMENT) {         if(eventType == XmlPullParser.START_DOCUMENT) {         Log.d("test", "Start document");         } else if(eventType == XmlPullParser.END_DOCUMENT) {         Log.d("test", "End document");         } else if(eventType == XmlPullParser.START_TAG) {         Log.d("test", "Start tag: "+xpp.getName());         } else if(eventType == XmlPullParser.END_TAG) {         Log.d("test", "End tag: "+xpp.getName());         } else if(eventType == XmlPullParser.TEXT) {         Log.d("test", "Text: "+xpp.getText());         }         eventType = xpp.next();        }    }}

输出结果:

Start document

Start tag: liu

Text:I am LIuliu

End tag: liu

Start tag: huo

Text: Missing Huohuo

End tag: huo

原创粉丝点击