Android-based SAX parsing XML file, androidsaxxml
1. Introduction to the SAX Parsing Method
SAX (Simple API for XML) is an XML parser with fast resolution speed and low memory usage. It is very suitable for Android and other mobile devices.
The SAX Parser is an event-based parser. The event-driven stream parsing method is to resolve the file sequence from the beginning to the end of the document. It cannot be paused or regressed. Its core is the event processing mode, which focuses on the event source and event processor. When an event is generated by the event source, an event can be processed by calling the corresponding processing method of the event processor. When the event source calls a specific method in the event processor, it also needs to pass the status information of the corresponding event to the event processor so that the event processor can determine its own behavior based on the provided event information. In addition, it does not need to parse the entire document. In the process of parsing the document in the content order, SAX will determine whether the characters currently read are a part of the legal XML syntax, if yes, the event is triggered. The so-called events are actually some callback methods, which are defined in the ContentHandler interface.
In the SAX interface, the event source is XMLReader In the org. xml. sax package. It parses the XML document through the parser () method and generates events. The event processor is the ContentHandle, DTDHandler, ErrorHandler, and EntityResolver interfaces in the org. xml. sax package. XMLReader connects to the ContentHandle, DTDHandler, ErrorHandler, and EntityResolver interfaces through the corresponding event processor registration method setXXX.
What is the event-driven model? It converts an XML document into a series of events, which are determined by the individual event processor. An object that can generate an event is called an event source, and an object that can respond to an event is called an event processor.
Advantage: you do not need to call the entire document and consume less resources. Especially in Embedded environments, such as android, it is strongly recommended to use SAX parsing.
Disadvantage: Unlike DOM parsing, the document remains in the memory for a long time, and the data is not persistent. If no data is saved after the event, the data will be lost.
Usage: The machine has performance restrictions.
Ii. Step 1 of SAX parsing. Create a SAXParserFactory object
SAXParserFactory spf = SAXParserFactory.newInstance();
2. According to the SAXParserFactory. newSAXParser () method, a SAXParser parser is returned.
SAXParser saxParser = spf.newSAXParser();
3. The instance is a DefaultHandler object.
Public class XMLContentHandler extends DefaultHandler {// receives the notification from the beginning of the document. When a document starts, call this method to perform preprocessing. @ Override public void startDocument () throws SAXException {...} // receives notifications starting with the element. This method is triggered when a start tag is read. Uri indicates the namespace of the element; // localName indicates the local name of the element (without a prefix); qName indicates the qualified name (with a prefix) of the element; attrs indicates the attribute set of the element. @ Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {...} // receives notifications of character data. The modification method is used to process the content read in the XML file. The first parameter is used to store the content of the file. The last two parameters // are the start position and length of the read string in this array. Use newSreing (ch, start, length) to obtain the content. @ Override public void characters (char [] ch, int start, int length) throws SAXException {...} // receives the notification at the end of the document. Call this method when an end tag is encountered. Uri indicates the namespace of the element; // localName indicates the local name of the element (without a prefix); name indicates the qualified name (with a prefix) of the element ). @ Override public void endElement (String uri, String localName, String qName) throws SAXException {...}
4. Call the SAXParser parser method to obtain XML data from the input source.
saxParser.parse(inputStream, handler); inputStream.close();
You can also use the parse method of XMLReader to obtain XML data from the input source.
5. Return the data set we need through DefaultHandler.
handler.getPersons();
Iii. parse XML code by using SAX 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/sax_button1" 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/SAX" /><Button android:id="@+id/sax_button2" 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/SAX" /><TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" />
3. Add the XMLContentHandler class
package com.zhangmiao.analyzexmldemo;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import java.util.ArrayList;import java.util.List;/** * Created by zhangmiao on 2016/12/13. */public class XMLContentHandler extends DefaultHandler { private List<Person> persons = null; private Person currentPerson; private String tagName = null; public List<Person> getPersons() { return persons; } @Override public void startDocument() throws SAXException { persons = new ArrayList<>(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("person")) { currentPerson = new Person(); currentPerson.setId(Integer.parseInt(attributes.getValue("id"))); } this.tagName = localName; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (tagName != null) { String data = new String(ch, start, length); if (tagName.equals("name")) { this.currentPerson.setName(data); } else if (tagName.equals("age")) { this.currentPerson.setAge(Short.parseShort(data)); } } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (localName.equals("person")) { persons.add(currentPerson); currentPerson = null; } this.tagName = null; }}
4. Add the AnalyzeSAM class
package com.zhangmiao.analyzexmldemo;import org.xml.sax.InputSource;import org.xml.sax.XMLReader;import java.io.InputStream;import java.util.List;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;/** * Created by zhangmiao on 2016/12/14. */public class AnalyzeSAX { public static List<Person> readXML(InputStream inputStream) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxParser = spf.newSAXParser(); XMLContentHandler handler = new XMLContentHandler(); saxParser.parse(inputStream, handler); inputStream.close(); return handler.getPersons(); } catch (Exception e) { e.printStackTrace(); } return null; } public static List<Person> readXML(InputSource inputSource) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser saxParser = spf.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); XMLContentHandler handler = new XMLContentHandler(); reader.setContentHandler(handler); reader.parse(inputSource); inputSource.getByteStream().close(); return handler.getPersons(); } catch (Exception e) { e.printStackTrace(); } return null; }}
5. 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 saxButton1 = (Button) findViewById(R.id.sax_button1); Button saxButton2 = (Button) findViewById(R.id.sax_button2); mTextView = (TextView) findViewById(R.id.text); saxButton1.setOnClickListener(this); saxButton2.setOnClickListener(this); } @Override public void onClick(View v) { String result = ""; inputStream = getResources().openRawResource(R.raw.itcase); switch (v.getId()) { case R.id.sax_button1: result += "--------- SAX1 ---------" + "\n"; if (inputStream == null) { result = "inputStream is null"; } else { List<Person> personList = AnalyzeSAX.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; case R.id.sax_button2: result += "--------- SAX2 ---------" + "\n"; InputSource inputSource = new InputSource(); inputSource.setByteStream(inputStream); if (inputSource == null) { result = "inputStream is null"; } else { List<Person> personList = AnalyzeSAX.readXML(inputSource); 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