Android creation and several xml parsing Methods

Source: Internet
Author: User


This article from


XML parsing scheme selection in Android system

The DOM parser parses an XML document into a tree model and puts it into the memory to complete the parsing. Then, operations on the document are completed on the tree model. The document tree in the memory will be several times the actual size of the document. The advantage of this is that the structure clearing and operation are convenient, and the trouble is that the system resources are greatly consumed. As a result, SAX overcomes the disadvantages of DOM, so analysis can begin immediately, rather than waiting for all the data to be processed. Moreover, because the application only checks data when reading data, it does not need to store the data in the memory, which is a huge advantage for large documents. In fact, the application does not even have to parse the entire document; it can stop parsing when a condition is full.

Whether to select DOM or SAX depends on the following factors:
Application Purpose: If you want to make changes to the data and output it as XML, DOM is the right option in most cases. It doesn't mean that you can't change data by using SAX, but the process is much more complicated, because you must copy the data instead of making changes to the data itself.
Data capacity:For large files, SAX is a better choice.
How to use data: If only a small amount of data is used, it may be better to use SAX to extract the data to the application. On the other hand, if you know that you will reference a large amount of information that has been processed in the future, SAX may not be an appropriate choice.
Speed requirements: The SAX implementation is usually faster than the DOM implementation.

Based on the above analysis, on handheld devices with limited memory and CPU resources based on the Android system, as long as we do not need to modify XML data or randomly access XML data, although SAX may require more coding, it is worthwhile to reduce memory and CPU consumption.

Besides, Android
The SDK contains the javax. xml. parsers package corresponding to JAXP, which corresponds to org. xml. SAX (of course, The org. w3c. DOM
And Android provides a package such as android. sax to facilitate
Handle development, based on standard methods such as JAXP and SAX, is not only less complex, even if there is a problem in the discussion group to find a solution is easier.


Pull Parsing is similar to Sax parsing. It is both lightweight and has been embedded in the Android kernel. Therefore, we do not need to add a third-party jar package to support Pull.

Pull Parsing is different from Sax parsing:

(1) pull reads the xml file and triggers the corresponding event. The call method returns a number.

(2) pull can control in the program where it is to be parsed to stop parsing.


Hello everyone, today I will explain how to create xml in android and some common xml parsing methods.

The first is creation. We use the XmlSerializer class to create an xml file, followed by parsing xml files. Common methods include dom, sax, and XmlPullParser. Due to the complexity of the sax code, this section only describes dom and XmlPullParser parsing. I will explain it separately in the next section. I will not discuss the advantages and disadvantages of several types of xml parsing.

For ease of understanding, I made a simple Demo. The first interface has three buttons. clicking the first button will create a books under the sdcard directory. xml file. The other two buttons call the dom and XmlPullParser methods to parse the xml file and display the results in a TextView. You can follow the steps below:

Step 1: Create an Android project named XmlDemo.

Step 2: Modify the main. xml layout file. The Code is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "" android: orientation = "vertical" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <Buttonandroid: id = "@ + id/btn1" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "create XML file"/> <Buttonandroid: id = "@ + id/btn2" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "DOM parsing XML"/> <Buttonandroid: id = "@ + id/btn3" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "XmlPullParse parsing XML"/> <TextViewandroid: id = "@ + id/result" android: layout_width = "fill_parent" android: layout_height = "wrap_content"/> </LinearLayout>


Step 3: Modify the main core program XmlDemo. java. The Code is as follows:

Package com. tutor. xml; import java. io. file; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import javax. xml. parsers. documentBuilder; import javax. xml. parsers. documentBuilderFactory; import javax. xml. parsers. parserConfigurationException; import org. w3c. dom. document; import org. w3c. dom. element; import org. w3c. dom. nodeList; import org. xml. sax. SAXException; impor T org. xmlpull. v1.XmlPullParser; import org. xmlpull. v1.XmlPullParserException; import org. xmlpull. v1.XmlPullParserFactory; import org. xmlpull. v1.XmlSerializer; import android. app. activity; import android. OS. bundle; import android. util. log; import android. util. xml; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; import android. wid Get. toast; public class XmlDemo extends Activity implements OnClickListener {private static final String BOOKS_PATH = "/sdcard/books. xml "; private Button mButton1, mButton2, mButton3; private TextView mTextView; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); setupViews () ;}// initialization work private void setupViews () {mTextView = (T ExtView) findViewById (R. id. result); mButton1 = (Button) findViewById (R. id. btn1); mButton2 = (Button) findViewById (R. id. btn2); mButton3 = (Button) findViewById (R. id. btn3); listener (this); mButton2.setOnClickListener (this); mButton3.setOnClickListener (this);} // create an xml File private void createXmlFile () {File linceseFile = new File (BOOKS_PATH ); try {linceseFile. createNewFile ();} catch (IOE Xception e) {Log. e ("IOException", "exception in createNewFile () method");} FileOutputStream fileos = null; try {fileos = new FileOutputStream (linceseFile);} catch (FileNotFoundException e) {Log. e ("FileNotFoundException", "can't create FileOutputStream");} XmlSerializer serializer = Xml. newSerializer (); try {serializer. setOutput (fileos, "UTF-8"); serializer. startDocument (null, true); serializer. s TartTag (null, "books"); for (int I = 0; I <3; I ++) {serializer. startTag (null, "book"); serializer. startTag (null, "bookname"); serializer. text ("Android tutorial" + I); serializer. endTag (null, "bookname"); serializer. startTag (null, "bookauthor"); serializer. text ("Frankie" + I); serializer. endTag (null, "bookauthor"); serializer. endTag (null, "book");} serializer. endTag (null, "books"); serializer. endDocumen T (); serializer. flush (); fileos. close ();} catch (Exception e) {Log. e ("Exception", "error occurred while creating xml file");} Toast. makeText (getApplicationContext (), "the xml file is created successfully! ", Toast. LENGTH_SHORT ). show () ;}// dom Parse xml File private void domParseXML () {file File = new File (BOOKS_PATH); DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance (); DocumentBuilder db = null; try {db = dbf. newDocumentBuilder ();} catch (ParserConfigurationException e) {e. printStackTrace ();} Document doc = null; try {doc = db. parse (file);} catch (SAXException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} Element root = doc. getDocumentElement (); NodeList books = root. getElementsByTagName ("book"); String res = "this result is parsed by dom:" + "/n"; for (int I = 0; I <books. getLength (); I ++) {Element book = (Element) books. item (I); Element bookname = (Element) book. getElementsByTagName ("bookname "). item (0); Element bookauthor = (Element) book. getElementsByTagName ("bookauthor "). item (0); res + = "Name:" + bookname. getFirstChild (). getNodeValue () + "" + "Author:" + bookauthor. getFirstChild (). getNodeValue () + "/n";} mTextView. setText (res);} // xmlPullParser parses the xml file private void xmlPullParseXML () {String res = "The result is parsed using XmlPullParse:" + "/n "; try {XmlPullParserFactory factory = XmlPullParserFactory. newInstance (); XmlPullParser xmlPullParser = factory. newPullParser (); xmlPullParser. setInput (Thread. CurrentThread (). getContextClassLoader (). getResourceAsStream (BOOKS_PATH), "UTF-8"); int eventType = xmlPullParser. getEventType (); try {while (eventType! = XmlPullParser. END_DOCUMENT) {String nodeName = xmlPullParser. getName (); switch (eventType) {case XmlPullParser. START_TAG: if ("bookname ". equals (nodeName) {res + = "title:" + xmlPullParser. nextText () + "";} else if ("bookauthor ". equals (nodeName) {res + = "Author:" + xmlPullParser. nextText () + "/n";} break; default: break;} eventType = xmlPullParser. next () ;}} catch (IOException e) {e. printStackTrace () ;}} catch (XmlPullParserException e) {e. printStackTrace ();} mTextView. setText (res);} // Response public void onClick (View v) {if (v = mButton1) {createXmlFile ();} else if (v = mButton2) {domParseXML ();} else if (v = mButton3) {xmlPullParseXML ();}}}


Step 4: because we have created a new file on the SD card, we need to add permissions, as shown in the following code (line 1 ):

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android=""      package="com.tutor.xml"      android:versionCode="1"      android:versionName="1.0">    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".XmlDemo"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>    <uses-sdk android:minSdkVersion="7" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> </manifest> 


Step 5: run the above project to check the effect:

Start the first interface:

Click create XML file to generate the books. xml file.

The contents of books. xml are as follows:

<? Xml version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?> <Books> <book> <bookname> Android tutorial 0 </bookname> <bookauthor> Frankie0 </bookauthor> </book> <bookname> Android tutorial 1 </bookname> <bookauthor> Frankie1 </bookauthor> </book> <bookname> Android tutorial 2 </bookname> <bookauthor> Frankie2 </bookauthor> </book> </ books>


Click the DOM parsing XML button:

Click XmlPullParse to parse XML:

OK ~ Let's talk about it today. Thx ~

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.