Android Pull parsing XML and androidpullxml

Source: Internet
Author: User

Android Pull parsing XML and androidpullxml
I. Introduction to the Pull Parsing Method

In addition to using SAX and DOM to parse XML files, you can also use the Android built-in Pull parser to parse XML files. The Running Method of the Pull parser is similar to that of the SAX Parser. It is also triggered by events. The Pull parsing method allows the application to completely control how the document is parsed. For example, to start and end element events, you can use parser. next () to enter the next element and trigger corresponding events. The Parser. getEventType () method is used to obtain the Event code value. parsing completes most of the processing at the beginning. The event is sent as a numeric code, so you can use a switch to process the event you are interested in. Pull Parsing is a process of traversing documents. Every time you call next (), nextTag (), nextToken (), and nextText (), the document is pushed forward and parser stays on some events, but it cannot be regressed. Set the document to Parser. It allows your application code to get events from the parser, which is the opposite of the event automatically pushed into the handler by the SAX Parser. The Pull parser is compact, lightweight, fast in resolution, and easy to use. It is very suitable for Android mobile devices. The Android system also uses the Pull Parser for parsing Various XML files, android officially recommends developers to use the Pull parsing technology. Pull Parsing is an open-source technology developed by a third party. It can also be used in JavaSE development.

What is the difference between SAX and Pull: The SAX Parser works by Automatically Processing the event processor, so it cannot control the Active Termination of event processing; the Pull parser is used to allow application code to actively retrieve events from the parser. Because it is an active event acquisition, it can no longer obtain events after the required conditions are met, end parsing.

Advantage: fast resolution and less resource occupation.

Disadvantage: the data is not persistent.

Usage: for large XML documents, but only a part of the documents is required.

2. Step 1 of PULL parsing. Construct an XmlPullParser object
XmlPullParser parser = Xml. newPullParser (); parser. setInput (inputStream, "UTF-8"); // sets the event source encoding
2. Get the Event Type
int eventType = parser.getEventType();
3. Get Text Content
// Determine whether the end node is reached while (eventType! = XmlPullParser. END_DOCUMENT) {switch (eventType) {// document start event, which can be initialized and processed by case XmlPullParser. START_DOCUMENT :... break; // start element event case XmlPullParser. START_TAG :... break; // End Element event case XmlPullParser. END_TAG :... break;} eventType = parser. next ();}

Call the parser. nextText () method to obtain the value of the next Text element.

Iii. PULL Parse XML Code 1. Create an XML file itcase. xml and put it in the res/raw folder.
<?xml version="1.0" encoding="UTF-8"?><persons>    <person id="23">        <name>liming</name>        <age>30</age>    </person>    <person id="20">        <name>lixiangmei</name>        <age>25</age>    </person></persons>

If there is no raw folder, create a raw folder under the res folder and create an xml file.

2. Modify the view
<Button        android:id="@+id/pull_button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_marginTop="@dimen/fab_margin"        android:gravity="center_horizontal"        android:text="@string/PULL" /><TextView        android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!" />
3. Add the AnalyzePull class
package com.zhangmiao.analyzexmldemo;import android.util.Xml;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlSerializer;import java.io.InputStream;import java.util.ArrayList;import java.util.List;/** * Created by zhangmiao on 2016/12/14. */public class AnalyzePull {    public static List<Person> readXML(InputStream inputStream) {        XmlPullParser parser = Xml.newPullParser();        try {            parser.setInput(inputStream, "UTF-8");            int eventType = parser.getEventType();            Person currentPerson = null;            List<Person> persons = null;            while (eventType != XmlPullParser.END_DOCUMENT) {                switch (eventType) {                    case XmlPullParser.START_DOCUMENT:                        persons = new ArrayList<>();                        break;                    case XmlPullParser.START_TAG:                        String name = parser.getName();                        if (name.equalsIgnoreCase("person")) {                            currentPerson = new Person();                            currentPerson.setId(                                    new Integer(parser.getAttributeValue(null, "id"))                            );                        } else if (currentPerson != null) {                            if (name.equalsIgnoreCase("name")) {                                currentPerson.setName(parser.nextText());                            } else if (name.equalsIgnoreCase("age")) {                                currentPerson.setAge(new Short(parser.nextText()));                            }                        }                        break;                    case XmlPullParser.END_TAG:                        if (parser.getName().equalsIgnoreCase("person")                                && currentPerson != null) {                            persons.add(currentPerson);                            currentPerson = null;                        }                        break;                }                eventType = parser.next();            }            inputStream.close();            return persons;        } catch (Exception e) {            e.printStackTrace();        }        return null;    }}
4. Modify the MainActivity class
package com.zhangmiao.analyzexmldemo;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.util.Log;import android.view.View;import android.view.Menu;import android.view.MenuItem;import android.widget.Button;import android.widget.TextView;import org.xml.sax.InputSource;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStreamWriter;import java.io.StringWriter;import java.util.List;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private static final String TAG = "AnalyzeXMLDemo";    private TextView mTextView;    private InputStream inputStream;    @Override    protected void onCreate(Bundle savedInstanceState) {        Log.v(TAG, "onCreate");        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });        Button pullButton = (Button)findViewById(R.id.pull_button);        mTextView = (TextView) findViewById(R.id.text);        pullButton.setOnClickListener(this);    }    @Override    public void onClick(View v) {        String result = "";        inputStream = getResources().openRawResource(R.raw.itcase);        switch (v.getId()) {            case R.id.pull_button:                result += "--------- PULL ---------" + "\n";                File xmlFile = new File("myitcast.xml");                if (inputStream == null) {                    result = "inputStream is null";                } else {                    List<Person> personList = AnalyzePull.readXML(inputStream);                    if (personList != null) {                        for (int i = 0; i < personList.size(); i++) {                            String message = "id = " + personList.get(i).getId() + " , name = " + personList.get(i).getName()                                    + " , age = " + personList.get(i).getAge() + ".\n";                            result += message;                        }                    }                }                mTextView.setText(result);               break;            default:                break;        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

References:

Http://www.open-open.com/lib/view/open1392780226397.html

Http://www.cnblogs.com/weixing/archive/2013/08/07/3243366.html

Http://www.tuicool.com/articles/IvQvyq

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.