Parsing xml files using androidsax (2)

Source: Internet
Author: User
In the previous article, we briefly introduced a method of parsing xml by using sax. it inherits the defaultHandler method and overrides several of the methods. In the previous article, we briefly introduced a method of parsing xml by using sax. it inherits the defaultHandler method and overrides several of the methods.

The second method is to use the RootElement class for parsing. the RootElement has a built-in ulthandler subclass,

The source code of RootElement is as follows:


public class RootElement extends Element {    final Handler handler = new Handler();    /**     * Constructs a new root element with the given name.     *     * @param uri the namespace     * @param localName the local name     */    public RootElement(String uri, String localName) {        super(null, uri, localName, 0);    }    /**     * Constructs a new root element with the given name. Uses an empty string     * as the namespace.     *     * @param localName the local name     */    public RootElement(String localName) {        this("", localName);    }    /**     * Gets the SAX {@code ContentHandler}. Pass this to your SAX parser.     */    public ContentHandler getContentHandler() {        return this.handler;    }    class Handler extends DefaultHandler {        Locator locator;        int depth = -1;        Element current = null;        StringBuilder bodyBuilder = null;        @Override        public void setDocumentLocator(Locator locator) {            this.locator = locator;        }        @Override        public void startElement(String uri, String localName, String qName,                Attributes attributes) throws SAXException {            int depth = ++this.depth;            if (depth == 0) {                // This is the root element.                startRoot(uri, localName, attributes);                return;            }            // Prohibit mixed text and elements.            if (bodyBuilder != null) {                throw new BadXmlException("Encountered mixed content"                        + " within text element named " + current + ".",                        locator);            }            // If we're one level below the current element.            if (depth == current.depth + 1) {                // Look for a child to push onto the stack.                Children children = current.children;                if (children != null) {                    Element child = children.get(uri, localName);                    if (child != null) {                        start(child, attributes);                    }                }            }        }        void startRoot(String uri, String localName, Attributes attributes)                throws SAXException {            Element root = RootElement.this;            if (root.uri.compareTo(uri) != 0                    || root.localName.compareTo(localName) != 0) {                throw new BadXmlException("Root element name does"                        + " not match. Expected: " + root + ", Got: "                        + Element.toString(uri, localName), locator);            }            start(root, attributes);        }        void start(Element e, Attributes attributes) {            // Push element onto the stack.            this.current = e;            if (e.startElementListener != null) {                e.startElementListener.start(attributes);            }            if (e.endTextElementListener != null) {                this.bodyBuilder = new StringBuilder();            }                        e.resetRequiredChildren();            e.visited = true;        }        @Override        public void characters(char[] buffer, int start, int length)                throws SAXException {            if (bodyBuilder != null) {                bodyBuilder.append(buffer, start, length);            }        }        @Override        public void endElement(String uri, String localName, String qName)                throws SAXException {            Element current = this.current;            // If we've ended the current element...            if (depth == current.depth) {                current.checkRequiredChildren(locator);                // Invoke end element listener.                if (current.endElementListener != null) {                    current.endElementListener.end();                }                // Invoke end text element listener.                if (bodyBuilder != null) {                    String body = bodyBuilder.toString();                    bodyBuilder = null;                    // We can assume that this listener is present.                    current.endTextElementListener.end(body);                }                // Pop element off the stack.                this.current = current.parent;            }            depth--;        }    }}

The above is the source code of the RootElement class. from the source code, we can see that it only takes a simple look at defaultHandler.


For specific applications, refer to the test source code I wrote.


/*** Second method for parsing xml using sax * using XMLReader is also a method of sax * @ return */private String saxParseSecond () {// read the xml file InputStream inputStream under src = this. getClass (). getClassLoader (). getResourceAsStream ("saxTest. xml "); SAXParserFactory factory = SAXParserFactory. newInstance (); try {SAXParser parse = factory. newSAXParser (); XMLReader reader = parse. getXMLReader (); reader. setContentHandler (getRootElement (). getContentHandler (); reader. parse (new InputSource (inputStream);} catch (ParserConfigurationException e) {e. printStackTrace ();} catch (SAXException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} return result ;}


/***** @ Return returns the rootElement */private RootElement getRootElement () {/* rootElement indicates the root node, the parameter is the tagName */RootElement rootElement = new RootElement ("classes") of the root node./* obtain a type of subnode and set corresponding events for it. * Note that, although we only set a group event once, all * groups under the root node in our document can trigger this event. **/Element groupElement = rootElement. getChild ("group"); // triggered when reading the start position of an Element, as shown in
 
  
GroupElement. setStartElementListener (new StartElementListener () {@ Override public void start (Attributes attributes) {// Log. I ("TEST", "start"); String groupName = attributes. getValue ("name"); String groupNum = attributes. getValue ("num"); result = result + "groupName =" + groupName + "groupNum =" + groupNum + "\ n ";}}); // triggered when reading the end position of an element, as shown in Reading
 GroupElement. setEndElementListener (new EndElementListener () {@ Override public void end () {}}); Element personElement = groupElement. getChild ("person"); // Read
 
  
Tag triggers the personElement. setStartElementListener (new StartElementListener () {@ Overridepublic void start (Attributes attributes) {String personName = attributes. getValue ("name"); String age = attributes. getValue ("age"); result = result + "personName =" + personName + "age =" + age + "\ n" ;}}); // Read
 Tag triggers the personElement. setEndElementListener (new EndElementListener () {@ Overridepublic void end () {}}); Element chinese = personElement. getChild ("chinese"); // chinese. setTextElementListener (new TextElementListener () {// @ Override // public void end (String body) {// TODO Auto-generated method stub //} // @ Override // public void start (Attributes attributes) {// TODO Auto-generated method stub //}); // triggered when the end of the text is read, the body is the content of the text in chinese. setEndTextElementListener (new EndTextElementListener () {@ Override public void end (String body) {Pattern p = Pattern. compile ("\ s * | \ t | \ r | \ n"); Matcher m = p. matcher (body); body = m. replaceAll (""); result = result + "chinese =" + body ;}}); Element english = personElement. getChild ("english"); english. setEndTextElementListener (new EndTextElementListener () {@ Override public void end (String body) {Pattern p = Pattern. compile ("\ s * | \ t | \ r | \ n"); Matcher m = p. matcher (body); body = m. replaceAll (""); result = result + "english =" + body + "\ n" ;}}); return rootElement ;}


We all know the method of parsing xml through the SAXParser object. here we can see from the code that we use another object XMLReader for parsing. what is the relationship and difference between the two?

In fact, SAXParser is defined in SAX 1.0, while XMLReader started to appear in 2.0. You can think that XMLReader is used to replace SAXParser parsing. the Two basically do the same thing, but XMLReader is more powerful.

In addition to the getXMLReader method of SAXParser, XMLReader can be obtained in either of the following ways.

XMLReader parser=XMLReaderFactory.createXMLReader(); (1)XMLReader parser=XMLReaderFactory.createXMLReader(String className); (2)


The above is the content of the android sax parsing xml file (2). For more information, see PHP Chinese website (www.php1.cn )!

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.