Android - Pull Analysis

Pull parsing

(1) Overview
1. Pull parser is an open source Java project, and the Android system internally parses xml files in this way. Pull is lightweight parsing. Pull is already embedded in the Android kernel, so there is no need to add a third-party jar package to support Pull.

2. Pull uses an event trigger mechanism when reading XML files. Events here refer to document start, tag start, tag end, document end , etc. Pull represents events as integer data, and different events are represented by different integers, which greatly simplifies the writing of parsing code.

3. Pull parses XML documents in a streaming manner. Pull parsing can control where you want to parse and stop parsing in the program.

4. The Android system uses Pull to parse XML documents by default .



(2) Related classes/interfaces

1. XmlPullFactory class: Parser factory class, used to create parser objects.
2, XmlPullParser class: parser class for parsing XML documents.

(3) Common methods of XmlPullFactory class
public static XmlPullFactory newInstance()
Function: Returns an XmlPullFactory object.

(4) Common methods of XmlPullParser class

1.public void setInput(InputStream inputStream,String inputEncoding)
Role: Set the input stream object to be parsed.
Parameters - inputStream: input stream object
Parameters - inputEncoding: the encoding format of the xml document

2.public int getEventType()
Function: Returns the type value of the current event, the common event type value.
illustrate:
1) XmlPullParser.START_DOCUMENT: Document start
2) XmlPullParser.END_DOCUMENT: end of document
3) XmlPullParser.START_TAG: tag start
4) XmlPullParser.END_TAG: end of tag

3.public int next()
Role: Get the next parser event

4.public String getName()
Function: Returns the current element name that is the label name

5.public String getAttributeValue(int index)
Role: Returns the attribute value of the specified index value

 

(5) Use steps

Step 1. Create a parser factory object, sample code:
factory = XmlPullParserFactory.newInstance();

Step 2. Create a parser object, sample code:
XmlPullParser parser = factory.newPullParser();

Step 3. Get the input stream object, sample code:
InputStream in = new FileInputStream("d:/se2/day12/user.xml");

Step 4. Set the input stream object of the parser operation and set the encoding format. Example code:
parser.setInput(in,"urf-8");

Step 5. The following loop reads each node in the XML document at a time, sample code:
for(int type = parser.getEventType(); //Get the parsed event
    type != XmlPullParser.END_DOCUMENT;// not document end event
    type = parser.next()){ // get the next event
    // Write code to get each XML node in a loop, for example:
    String tagName = parser.getName();// Get the name of the current node
    ...

}

 


actual case:


package com.jxust.elts.dao;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.jxust.elts.entity.ExamInfo;
import com.jxust.elts.entity.Files;
import com.jxust.elts.entity.Question;
import com.jxust.elts.entity.User;
import com.jxust.elts.utils.HttpUtils;
import com.jxust.elts.utils.HttpUtils.RequestMethod;

import android.R.array;
import android.content.Context;
import android.util.Xml;

public class ExamBao_PullParse extends ExamDaoBase implements IExamDao {

	Files mFiles;
	
	public ExamBao_PullParse(Context context) {
		mFiles = getFiles(context); // Get the url of the currently downloaded file
	}

	@Override
	public ArrayList<Question> loadQuestions() {
		// ===========Pull parsing ===============
		ArrayList<Question> questions = new ArrayList<Question>();
		String url = mFiles.getUrl() + mFiles.getFnQuestion(); // get the full path
		InputStream in = null;
		try {
			in = HttpUtils.getInputStream(url, null, RequestMethod.GET);
			XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
			parser.setInput(in,"utf-8");
			for(int evenType = XmlPullParser.START_DOCUMENT; // The initial condition is to start from the start document event
					evenType != XmlPullParser.END_DOCUMENT; // The end loop is to judge whether the end document event has been reached
					evenType = parser.next()){ // skip to the next event after each execution
				if(evenType == XmlPullParser.START_TAG){ // start of tag
					String tagName = parser.getName();
					if("question".equals(tagName)){
						String answer = parser.getAttributeValue(null, "answer"); // The first is the namespace, the second is the attribute value
						ArrayList<String> answers = new ArrayList<String>();
						for(int i = 0;i < answer.length();i++){
							answers.add(answer.charAt(i)+"");
						}
						int score = Integer.parseInt(parser.getAttributeValue(null,"score"));
						int level = Integer.parseInt(parser.getAttributeValue(null, "level"));
						String title = parser.getAttributeValue(null,"title");
						StringBuilder options = new StringBuilder();
						for(int i = 4;i <= 7;i++){
							options.append(parser.getAttributeValue(i)).append("\n");
						}
						Question q = new Question(answers, level, score, title, options.toString());
						questions.add(q);
					}
				}
			}
			return questions;
		} catch (Exception e) {
			e.printStackTrace ();
		}finally {
			if(in != null){
				try {
					in.close(); // close the input stream resource
				} catch (IOException e) {
					e.printStackTrace ();
				}
			}
			HttpUtils.closeClient(); // Close the server service
		}
		return null;
	}

	@Override
	public ExamInfo loadExamInfo() {
		// ===========Pull parsing ===============
		String url = mFiles.getUrl() + mFiles.getFnExamInfo(); // this is the full address
		InputStream in = null;
		try {
			in = HttpUtils.getInputStream(url, null, HttpUtils.RequestMethod.GET);
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser(); // Create parser for Pull parsing
			parser.setInput(in,"utf-8"); // Set the input stream object to be parsed, parameter 1: input stream object, parameter 2: input stream object encoding method
			ExamInfo examInfo = new ExamInfo();
			for(int eventType = XmlPullParser.START_DOCUMENT; // loop start is start document
					eventType != XmlPullParser.END_DOCUMENT; // End of loop is end of document
					eventType = parser.next()){ // Skip to the next event after one operation
				if(eventType == XmlPullParser.START_TAG){ // If the tag starts
					String tagName = parser.getName(); // Get the tag name
					if("exam info".equals(tagName)){
						examInfo.setSubjectTitle(parser.getAttributeValue(0)); // get the exam name
						examInfo.setLimitTime(Integer.parseInt(parser.getAttributeValue(1))); // Get the exam time
						examInfo.setQuestionCount(Integer.parseInt(parser.getAttributeValue(2))); // Get the number of exam questions
						return examInfo; // there is only one so return directly
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace ();
		}finally {
			if(in != null){
				try {
					in.close(); // close the input stream
				} catch (IOException e) {
					e.printStackTrace ();
				}	
			}
			HttpUtils.closeClient(); // also close the server connection
		}
		return null;
	}

	@Override
	protected void loadUsers() {
		String url = mFiles.getUrl() + mFiles.getFnUser(); // Get the complete Url address
		InputStream in = null;
		try {
			 in = HttpUtils.getInputStream(url, null, HttpUtils.RequestMethod.GET);
			 XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
			 parser.setInput(in,"utf-8");
			 for(int evenType = XmlPullParser.START_DOCUMENT;
					 evenType != XmlPullParser.END_DOCUMENT;
					 evenType = parser.next ()) {
				if(evenType == XmlPullParser.START_TAG){
					String tagName = parser.getName();
					if("user".equals(tagName)){
						int id = Integer.parseInt(parser.getAttributeValue(null, "id"));
						String name = parser.getAttributeValue(null, "name");
						String password = parser.getAttributeValue(null,"passsword");
						String phone = parser.getAttributeValue(null, "phone");
						String email = parser.getAttributeValue(null, "email");
						User user = new User(id, name, password, phone, email);
						mUsers.put(user.getId(), user); // save the user locally
					}
				}
			 }
		} catch (Exception e) {
			e.printStackTrace ();
		}finally {
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}
			}
			HttpUtils.closeClient();
		}
	}
}

 

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="examInfo"> Exam Subject: core java Candidate ID: 1001\n
    Exam Duration: 10 minutes Number of Questions: 20</string>
    <string name="question">1. It is ______ that can be directly recognized by computer hardware. \n
A. Advanced Language\n
B. Intermediate Language\n
C. Assembly language\n
D. Machine Language</string>
    <string name="app_name">Online exam</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    
    <string name="root_url">http://10.0.2.2/</string>
    <string name="user_txt">elts-txt/users.txt</string>
    <string name="exam_info_txt">elts-txt/exam_info.txt</string>
    <string name="question_txt">elts-txt/questions.txt</string>
    <string name="user_xml">elts-xml/users.xml</string>
    <string name="exam_info_xml">elts-xml/exam_info.xml</string>
    <string name="question_xml">elts-xml/questions.xml</string>
    <string name="user_json">elts-json/users.json</string>
    <string name="exam_info_json">elts-json/exam_info.json</string>
    <string name="question_json">elts-json/questions.json</string>
    <!--
          parse_mode represents the type of parsed file and has four optional values:
    	txt: text file
    	pull_xml: xml file
    	sax_xml: sax parsing, the xml file used is the same as pull_xml
    	json: json file
    -->
    <string name="parse_mode">pull_xml</string>
    <string name="title_activity_login">Login window</string>
    <string name="title_activity_exam">Exam Window</string>
    <string name="title_activity_main_menu">Exam Main Window</string>

</resources>

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326689989&siteId=291194637