Android Development 8--Use pull parser to read and write XML files

Source: Internet
Author: User

First, the basic introduction

There are many ways to parse XML, including sax and Dom, and it is highly recommended in Android to parse XML in Xmlpull mode. Xmlpull not only can be used on Android as well as Javase, but in javase environments it is necessary to get the Xmlpull-dependent class library, Kxml2-2.3.0.jar,xmlpull_1_1_3_4c.jar.

Jar Package Download URL
http://www.xmlpull.org/
http://kxml.sourceforge.net/

Second, examples

The declaration read to XML returns the number 0 start_document;
The end of reading to XML returns the number 1 end_document;
The start tag read to XML returns the number 2 Start_tag
The end tag read to XML returns the number 3 End_tag
Text read to XML returns the number 4 text

<?xml version= "1.0" encoding= "UTF-8"?>
<people>
	<person id= "001" >
		<name>xy1 </name>
		<age>22</age>
	</person>
	<person id= "002" >
		<name>xy2 </name>
		<age>22</age>
	</person>
</people>

Package cn.xy.service;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.util.ArrayList;

Import java.util.List;
Import Org.xmlpull.v1.XmlPullParser;

Import Org.xmlpull.v1.XmlSerializer;
Import android.util.Xml;

Import Cn.xy.model.Person; /** * Using pull parser to parse XML * * @author XY * */public class Personservice {/** * reading data from XML file * * @param XML XML
		Part input stream/public list<person> getpeople (InputStream xml) throws Exception {list<person> = null;

		person person = null;

		Use the API provided by Android to quickly get pull parser xmlpullparser Pullparser = Xml.newpullparser ();

		Sets the XML data Pullparser.setinput (XML, "UTF-8") that needs to be parsed;

		Get Event int = Pullparser.geteventtype ();
			If parsing to the end while (event!= xmlpullparser.end_document)//document END {String nodename = Pullparser.getname ();
					Switch (event) {case xmlpullparser.start_document://Document Start LST = new arraylist<person> ();
				Break
				Case XMLPULLPARSER.START_TAG://Label start	if ("Person". Equals (NodeName)) {String id = pullparser.getattributevalue (0);
						person = new person ();
					Person.setid (ID);
						} if ("Name". Equals (NodeName)) {String name = Pullparser.nexttext ();
					Person.setname (name);
						} if (' Age '. Equals (nodename)) {int age = integer.valueof (Pullparser.nexttext ());
					Person.setage (age);
				} break;
						Case Xmlpullparser.end_tag://Tag End if ("person". Equals (NodeName)) {Lst.add (person);
					person = null;
			} break; event = Pullparser.next ();
	Next label} return LST; /** * Writes data to XML * * @param OS * @param person * @throws Exception/public void SaveDataToXML (outputstre
		Am OS, list<person> lst) throws Exception {XmlSerializer xs = xml.newserializer ();
		Xs.setoutput (OS, "UTF-8");
		Xs.startdocument ("UTF-8", true);
		Xs.starttag (NULL, "people");
			for (person P:lst) {Xs.starttag (null, ' person '); Xs.attribUte (NULL, "person", P.getid ());
			Xs.starttag (NULL, "name");
			Xs.text (P.getname ());

			Xs.endtag (NULL, "name");
			Xs.starttag (NULL, "age");
			Xs.text (P.getage (). toString ());

			Xs.endtag (NULL, "age");
		Xs.endtag (null, "person");
		} Xs.endtag (NULL, "people");
		Xs.enddocument ();
		Os.flush ();
	Os.close ();
 }
}
public class TestClass extends Androidtestcase
{public
	void Testpeople () throws Exception
	{
		Personservice PS = new Personservice ();
		InputStream XML = This.getclass (). getClassLoader (). getResourceAsStream ("person.xml");
		list<person> LST = ps.getpeople (XML);
		Assert.assertequals ("XY1", Lst.get (0). GetName ());

	public void Testsave () throws Exception
	{
		personservice PS = new Personservice ();
		list<person> lst = new arraylist<person> ();
		Lst.add (New person ("0001", "XY0001");
		Lst.add (New person ("0002", "XY0002");
		File XmlFile = new file (This.getcontext (). Getfilesdir (), "Xy.xml"); Data/data/package name/files
		outputstream os = new FileOutputStream (xmlFile);
		Ps.savedatatoxml (OS, LST);
	}

Related Article

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.