Android advanced method for parsing XML

Source: Internet
Author: User

<1> what is SAX? I used to only hear about SAX and SAX, but I never touched it. I want to take a note today. SAX is short for Simple API for XML. It is both an interface and a package. SAX is an xml parser with high resolution speed and low memory usage. It is suitable for Android and other mobile devices. Unlike DOM parsing, DOM puts all data into memory for parsing. The event-driven method is used to parse XML files. That is to say, it does not need to parse the entire document. In the process of parsing documents in order of content, SAX will judge whether the characters currently read are a part of the legal XML syntax. If yes, the event will be triggered. The so-called events are actually some callback methods defined in the ContentHandler interface. Another point is that after obtaining the information you need during the parsing process, you can terminate the parsing at any time. It does not have to wait until all the files are parsed. Advantages and disadvantages: SAX uses stream processing. When a tag is encountered, it does not record the previously encountered tag, that is, when processing a tag, for example, in the startElement method, the information obtained is the Tag Name and attribute. As for the nested structure inside the tag, information related to its structure, such as the upper-layer label, lower-layer label, and the name of its brother node, is unknown. In fact, the structure information of the XML file is lost. If you need this information, you can only process it yourself in the program. Therefore, compared with DOM, it is not convenient for SAX to process XML documents, and the process of SAX processing is more complex than DOM. <2> startDocument (), a common method of the ContentHandler interface, can be used to call this method when a document starts. The endDocument () corresponds to the preceding method. When the document ends, you can call this method to complete the work. StartElement (String namespaceURI, String localName, String qName, Attributes atts) triggers this method when a start tag is read. NamespaceURI is the namespace, localName is the tag name without the namespace prefix, and qName is the tag name with the namespace prefix. You can use atts to obtain all the attribute names and corresponding values. It should be noted that an important feature of SAX is its stream processing. When a tag is encountered, it does not record the previously encountered tag, that is, in the startElement () method, all the information you know is the name and attribute of the tag. As for the nested structure of the tag, the name of the Upper-layer tag, it is unknown whether there are sub-Meta and other information related to the structure, and you need your program to complete it. This makes it easier to program and process SAX than DOM. EndElement (String uri, String localName, String name) corresponds to the preceding method. This method is called when an end tag is encountered. Characters (char [] ch, int start, int length) is used to process the content read in the XML file. For example, <name> xiaosi </name> is used to obtain the value in the name tag. The first parameter is used to store the file content. The next two parameters are the start position and length of the read String in this array. You can obtain the content using new String (ch, start, length. <? Xml version = "1.0"?> ----------> StartDocument () <student> ----------> startElement <name> ----------> startElement quota ----------> characters </name> ----------> endElement <id> ----------> startElement 090105 ----------> characters </id> ----------> endElement </student> ---------> endElement document ended ---------> startDocument () <3> generally, the following five steps are involved in parsing an XML file using SAX: 1. Create a SAXParserFactory object (it is easy to know through the class name that it is implemented using the factory method mode ); 2. Call newS in SAXParserFactory The AXParser method creates a SAXParser object. 3. Call the getXMLReader method in SAXParser to obtain an XMLReader object. 4. register the event processing interface in XMLReader, generally, there are four types: ContentHandler, ErrorHandler, DTDHandler, and EntityHandler. 5. Call the parse method in XMLReader to parse the specified XML string object. Implementation: Note: Because ContentHandler is an interface, it is inconvenient to use and all methods need to be implemented, but some methods will not be used. Therefore, SAX has developed a Helper class for it: DefaultHandler, which implements this interface, but all its methods are empty. During implementation, you only need to inherit this class and then reload the corresponding method to [java] package xiaosi. sax; import java. io. IOException; import java. io. stringReader; import javax. xml. parsers. parserConfigurationException; import javax. xml. parsers. SAXParserFactory; import org. apache. http. httpResponse; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. protocol. HTTP; import org. apache. http. util. entityUtils; import org. xml. sax. inputSource; import org. xml. sax. SAXException; 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 XMLSAXActivity extends Activity {private Button button = null; private String xmlContent = ""; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); button = (Button) findViewById (R. id. button); button. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {try {getWeatherArray ("beijing"); SAXParserFactory saxFactory = SAXParserFactory. newInstance (); XMLReader xmlReader = saxFactory. newSAXParser (). getXMLReader (); xmlReader. setContentHandler (new MyContentHandler (); String xml = "<student> <name> xiaosi </name> <id> 090105 </id> </student>"; xmlReader. parse (new InputSource (new StringReader (xml);} catch (SAXException e) {e. printStackTrace ();} catch (ParserConfigurationException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace () ;}}) ;}} MyContentHandler: [java] package xiaosi. sax; import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler; import android. util. log; public class MyContentHandler extends DefaultHandler {String tag = "XIAOSI"; @ Override public void startDocument () throws SAXException {Log. I (tag, "startDocument") ;}@ Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {Log. I (tag, "startElement") ;}@ Override public void characters (char [] ch, int start, int length) throws SAXException {Log. I (tag, "characters") ;}@ Override public void endDocument () throws SAXException {Log. I (tag, "endDocument") ;}@ Override public void endElement (String uri, String localName, String qName) throws SAXException {Log. I (tag, "endElement ");}}

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.