Getting started with XMLPullParser

2019-02-25 19:03发布

I am trying to use XMLPullParser but I cannot find any useful tutorials. Based off of the instructions on http://xmlpull.org/ I need to download an implementation of XMLPullParser as a jar file and then add it to my class path. However I cannot find any link to any jar file that works. Does anyone know where I might be able to find a jar file I can download.

Thanks

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-25 19:49

Ok, here it is for you.

From the official doc :

XmlPull API Implementations:

  1. XNI 2 XmlPull
  2. XPP3/MXP1
  3. KXML2

Here i use KXML2.

Steps :

  1. Download KXML2 jar file from here.
  2. Create a new java project

enter image description here

  1. Create a new class

enter image description here

  1. Right click the java project -> Properties -> Java Build path -> Libraries -> Add external jar's -> Add downloaded kxml2 jar file.

enter image description here

  1. Java code

    import java.io.IOException;
    import java.io.StringReader;
    import org.xmlpull.v1.XmlPullParser;
    import org.xmlpull.v1.XmlPullParserException;
    import org.xmlpull.v1.XmlPullParserFactory;
    
    public class XmlPullparserBasic {
    public static void main (String args[]) throws XmlPullParserException, IOException
    {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
    
        int eventType = xpp.getEventType();
    
        while (eventType != XmlPullParser.END_DOCUMENT) {
         if(eventType == XmlPullParser.START_DOCUMENT) {
             System.out.println("Start document");
         } else if(eventType == XmlPullParser.START_TAG) {
             System.out.println("Start tag "+xpp.getName());
         } else if(eventType == XmlPullParser.END_TAG) {
             System.out.println("End tag "+xpp.getName());
         } else if(eventType == XmlPullParser.TEXT) {
             System.out.println("Text "+xpp.getText());
         }
         eventType = xpp.next();
        }
    
        System.out.println("End document");
    
      }
    
    }
    

Output :

enter image description here

Hope it helps!

查看更多
登录 后发表回答