Android_xml File parsing

Source: Internet
Author: User

There are two basic parsing methods for parsing XML files, one called sax, and the other called Dom:

1. Dom generates and parses XML documents
DOM, full name Document Object model, defines a set of interfaces for the parsed version of an XML document. The parser reads the entire document and then constructs a tree structure that resides in memory, and the code can then manipulate the tree structure using the DOM interface. Advantages: The entire document tree in memory, easy to operate, support delete, modify, rearrange and other functions; disadvantage: The entire document into memory (including useless nodes), waste time and space; Use cases: Once the document is parsed, the data must be accessed multiple times, and the hardware resources are sufficient (memory, CPU).

2. Sax generates and parses XML documents
Sax has emerged to solve the DOM problem. SAX, event-driven. When the parser discovers the start of an element, the end of an element, text, the beginning or end of a document, and so on, the programmer writes the code that responds to these events and saves the data. Pros: No need to transfer the entire document in advance, consume less resources, SAX parser code is smaller than DOM parser code, suitable for applets, download. Cons: not persistent; After the event, if the data is not saved, then the data is lost, stateless, only the text can be obtained from the event, but the text is not known which element; use case: Applet; only a small amount of XML documents, little back access, less machine memory, etc.

This is where you use Sax to parse the XML.

The SAX full name Simpleapi for XML is both an interface and a package. As an interface, sax is a standard interface for event-driven XML parsing.
(1) Sax works simply by scanning the document sequentially, notifying the event handler when the document starts and ends, elements (element), and so on, and the event handler acts accordingly, and then continues the same scan, Until the end of the document.

(2) most SAX implementations will produce the following types of events :
-Trigger the document handling event at the beginning and end of the document;
-Trigger element events before and after each XML element within the document is parsed;
-Any metadata is usually delivered by a single event;
-Generates a DTD or schema event when processing a DTD or schema of a document;
-Generates an error event to notify the host application of parsing errors;

(3) Sax model

(4) parsing the document process
For this document
A<doc>
3<para>4Hello world!5</para>6
</doc>7
A total of 7 events were generated, including:
-Create event handlers;
-Create a SAX parser;
-Assigning an event handler to the parser;
-Parse the document and send the event to the handler;

The ContentHandler interface is a special sax interface in the Java class package, where there are 5 commonly used interfaces:
Startdocument (): Receive notification of the beginning of a document.
Enddocument (): Receive notification of the end of a document.
Startelement (String uri, String localname, String qName, Attributes atts)
Receive notification of the beginning of an element.
EndElement (String uri, String localname, String qName): Receive notification of the end of an element.
Characters (char[] ch, int start, int length): Receive notification of character data.

(5) Example
Xmlactivity.java

Package Chay.xml;import Java.io.stringreader;import Javax.xml.parsers.saxparserfactory;import Org.xml.sax.inputsource;import Org.xml.sax.xmlreader;import Android.app.activity;import Android.os.Bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class XMLActivity Extends Activity {private Button parsebtn; String xmlstr = "<school><stu id= ' 001 ' ><name>Chay</name><sex> male </sex><age >22</age></stu><stu id= ' 002 ' ><name>Mark</name><sex> female </sex><age >40</age></stu></school> "; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (Savedinstancestate), Setcontentview (r.layout.activity_main);p arsebtn = (Button) findViewById ( R.ID.PARSEBTN);p Arsebtn.setonclicklistener (New Parsebuttonlistener ());} button Listener, click to open Thread class Parsebuttonlistener implements Onclicklistener {public void OnClick (View arg0) {thread t = new Xmlthre AD (); t.stArt ();}} Class Xmlthread extends Thread {@Overridepublic void run () {try {//Create a saxparserfactorysaxparserfactory factory = Saxpars Erfactory.newinstance (); XMLReader reader = Factory.newsaxparser (). Getxmlreader ();//Set Content processor Reader.setcontenthandler for XMLReader (new Mycontenthandler ());//Start parsing XML and invoke the corresponding event response function Reader.parse (new InputSource (new StringReader (XMLSTR)));} catch (Exception e) {e.printstacktrace ();}}}}
Xmlcontenthandler.java
Package Chay.xml;import Org.xml.sax.attributes;import Org.xml.sax.saxexception;import Org.xml.sax.helpers.defaulthandler;public class Xmlcontenthandler extends DefaultHandler {String name, sex, age; String tagName; @Overridepublic void Startdocument () throws Saxexception {System.out.println ("---start Document---");}    @Overridepublic void Enddocument () throws Saxexception {System.out.println ("---end Document---");} URI: Gets the namespace (NamespaceURI, namespace, to prevent label name) of the currently parsing tag//localname: Get no prefix tag <abc:name> get name//qname: Get prefixed label &L  T;abc:name> get Abc:name//attr: Get the properties of the tag <stu id= "001" > Get id= "001" @Overridepublic void startelement (String uri,  String LocalName, String Qname,attributes attr) throws saxexception {tagName = localname;if (Localname.equals ("Stu")) {// Gets all properties of the label for (int i = 0; i < attr.getlength (); i++) {System.out.println (Attr.getlocalname (i) + "=" + Attr.getvalue (i)) ;}}} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {//After parsing the Stu label, print all the obtained data TagName = "", if (Localname.equals ("Stu")) {this.prinout ();}} @Overridepublic void characters (char[] ch, int start, int length) throws Saxexception {String temp = new String (CH, start, Length), if (Tagname.equals ("name")) {name = new string (temp),} else if (Tagname.equals ("Sex")) {sex = new string (temp);} E LSE if (Tagname.equals ("Age")) {age = new String (temp);}} private void Prinout () {System.out.println ("Name--->" + name); SYSTEM.OUT.PRINTLN ("Sex--->" + Sex); System.out.println ("Age--->" + age);}
The above inheritance is DefaultHandler instead of ContentHandler, which is an adapter pattern because there are many methods in ContentHandler that are not implemented.


Android_xml File parsing

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.