XML parsing analysis provided by Android

Source: Internet
Author: User

Final

Code structure:

Code details:

Main. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: Orientation = "vertical" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "fill_parent" <br/> <textview <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: id = "@ + ID/textview" <br/> </linearlayout> <br/>

Beauties. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <beauties> <br/> <beauty> <br/> <Name> Lin Zhiling </Name> <br/> <age> 28 </age> <br /> </beauty> <br/> <Name> Yang Mi </Name> <br/> <age> 23 </age> <br/> </beauty> </P> <p> </beauties>

Activity Code

Package cn.com. sax; </P> <p> Import Java. io. inputstream; <br/> Import Java. util. arraylist; </P> <p> Import javax. XML. parsers. saxparser; <br/> Import javax. XML. parsers. saxparserfactory; </P> <p> Import Org. XML. sax. attributes; <br/> Import Org. XML. sax. inputsource; <br/> Import Org. XML. sax. xmlreader; <br/> Import Org. XML. sax. helpers. xmlreaderfactory; </P> <p> Import android. app. activity; <br/> Import android. OS. bundle; <Br/> Import android. sax. element; <br/> Import android. sax. endelementlistener; <br/> Import android. sax. endtextelementlistener; <br/> Import android. sax. rootelement; <br/> Import android. sax. startelementlistener; <br/> Import android. util. log; <br/> Import android. util. XML; <br/> Import android. widget. textview; <br/>/** <br/> * @ author chenzheng_java <br/> * @ description use android. parse the classes in the sax package <br/> */ <Br/> public class androidsaxactivity extends activity {<br/> private string result = "final result:/N "; <br/> private arraylist <beauty> beautylist = new arraylist <beauty> (); <br/> private Beauty = NULL; <br/> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); </P> <p>/* the following xmlreader parsing method is also a sax parsing method. <br/> * We use the same functions as saxparser. However, this function is more powerful. <br/> */<br/> try {<br/> log. I ("notification", "Start Parsing"); <br/> inputstream = This. getclassloader (). getresourceasstream ("beauties. XML "); <br/> saxparserfactory factory = saxparserfactory. newinstance (); <br/> saxparser parser = factory. newsaxparser (); <br/> xmlreader reader = parser. getxmlreader (); <br/> reader. setcontenthandler (getrootelement (). getcontenthandler (); <br/> reader. parse (New Inputsource (inputstream); <br/> log. I ("notification", "Resolution completed"); <br/>} catch (exception e) {<br/> E. printstacktrace (); <br/>}</P> <p> for (Beauty: beautylist) {<br/> result + = beauty. tostring () + "/N"; </P> <p >}</P> <p> textview = (textview) This. findviewbyid (R. id. textview); <br/> textview. settext (result ); </P> <p >}< br/>/** <br/> * @ return returns the rootelement of the configured processing mechanism. <br/> */ <br/> private rootelement Getrootelement () {</P> <p>/* rootelement indicates the root node, the parameter is the tagname */<br/> rootelement = new rootelement ("beauties") of the root node. <br/>/* obtain a type of subnode, and set the corresponding event for it <br/> * Note that although we only set the beauty event once, however, all <br/> * Beauty under the root node in our document can trigger this event. <Br/> **/<br/> element beautyelement = rootelement. getchild ("beauty"); <br/> // triggered when reading the start position of an element, for example, when reading <beauty> <br/> beautyelement. setstartelementlistener (New startelementlistener () {<br/> @ override <br/> Public void start (attributes) {<br/> log. I ("notification", "Start"); <br/> beauty = new beauty (); <br/>}< br/> }); <br/> // triggered when an element is read to its end position, such as </beauty> <br/> beautyelement. setendelementlistener (New endelementlistener () {<br/> @ override <br/> Public void end () {<br/> beautylist. add (beauty); <br/>}< br/>}); </P> <p> element nameelement = beautyelement. getchild ("name"); <br/> // triggered when the end of the text is read. The body here is the content part of the text <br/> nameelement. setendtextelementlistener (New endtextelementlistener () {<br/> @ override <br/> Public void end (string body) {<br/> beauty. setname (body); <br/>}< br/>}); </P> <p> element ageelement = beautyelement. getchild ("Age"); <br/> ageelement. setendtextelementlistener (New endtextelementlistener () {<br/> @ override <br/> Public void end (string body) {<br/> beauty. setage (body); <br/>}< br/>}); <br/> return rootelement; </P> <p >}</P> <p> private class beauty {<br/> string name; <br/> string age; <br/> Public String getname () {<br/> return name; <br/>}< br/> Public void setname (string name) {<br/> This. name = Name; <br/>}< br/> Public String getage () {<br/> return age; <br/>}< br/> Public void setage (string age) {<br/> This. age = age; <br/>}< br/> @ override <br/> Public String tostring () {<br/> return "Beauty information [age =" + age + ", name =" + name + "]"; <br/>}</P> <p >}< br/>}

Run the command to obtain the above Code.

------------------------------------------

Here we will talk about some classes provided by Android related to parsing XML.

Android. Sax package. Main Structure of the following classes and interfaces

There are two main classes: element and rootelement. You must note that when using the class, you must check which package you have imported and never reverse the wrong package, otherwise, you will be waiting to die in pain and sorrow.

The rootelement inherits from the element class and is only used to represent the root node of the document. Its methods are basically inherited from the element class. It defines only one method getcontenthandler (), which returns a contenthandler object of sax.

(I guess someone is confused here. Isn't the event-driven mode of sax parsing? Why is it still related to the root node in Dom. In fact, the answer is very simple. The bottom layer is parsed by using the sax method. Here, we only provide a few node-related methods for the convenience of users, we can use the thinking of nodes to operate on the sax parsing. After all, nodes are more organized than the event-driven sax nodes ).

The main methods of the element class are:

 

Nothing else can be said. Let's talk about the difference and connection between the getchild method and the requirechild method. Both methods obtain the child elements of the current element through tagname (Tag name. In the source code, requirechild is implemented in this way.Public element requirechild (string Uri, string localname) {<br/> element child = getchild (Uri, localname); </P> <p> If (requiredchilden = NULL) {<br/> requiredchilden = new arraylist <element> (); <br/> requiredchilden. add (child); <br/>}else {<br/> If (! Requiredchilden. contains (child) {<br/> requiredchilden. add (child); <br/>}</P> <p> return child; <br/>}

Here, requiredchilden is an arraylist <element>, which stores all the elements you have accessed. The biggest difference between the two is that when we use the requirechild method, during our parsing, if an element that has been accessed suddenly disappears (the ghost knows why ), this method will notify the user by throwing an exception.

 

 

------------------------------------------------------------------------

From the code, we can see that we set the event listener of the rootelement and its subnodes to specify the operations that should be performed during XML parsing. Then, we can get a contenthandler object through the getcontenthandler method. Then, use the setcontenthandler method of xmlreader to associate it with the parser.

------------------------------------------------------------------------

In fact, we can use this statement to parse XML. parse (inputstream, XML. encoding. utf_8, getrootelement (). getcontenthandler (); this XML class is a help class provided by Android. We will introduce it in detail later.

------------------------------------------------------------------------

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 following is an introduction:

In fact, xmlreader is an interface, so xmlreaderfactory needs a concrete class which implements this interface to get an instance, once the factory get the class's name, then it use Java reflection to create an instantiated object and return it, org. apache. xerces. parsers. saxparser is such a class in case. </P> <p> if you try to use API (1) to get an xmlreader instance, xmlreaderfactory first try to get the xmlreader's classname by retrieving the system property with key "org. XML. sax. driver ", if this property has set with an appropriate classname, the factory use this name instantiated an object and return; if this property not set, then it fallback to class parserfactory, parserfactory then retrieves a system property named "org. XML. sax. parser "to get a parser's classname to instantiate, if this property is not set too, Your invocation to get a xmlreader will fail and a saxexception with the message" system property Org. XML. sax. driver not specified "is throwed, otherwise, the parserfactory will return an parser instance with the specified parser name to xmlreaderfactory, and xmlreaderfactory use this parser to instantiate an parserlike adapter new parseradapter (parser ), so the xmlreader you get is an instance of the classnew parseradapter. </P> <p> SO, in conclusion, in order to make it works as fine as you expected, you can do as the following ways to get an xmlreader: <br/> (1) <br/> xmlreader parser = xmlreaderfactory. createxmlreader (string classname); <br/> (2) <br/> system. setproperty ("org. XML. sax. driver "," org. apache. xerces. parsers. saxparser "); <br/> xmlreader parser = xmlreaderfactory. createxmlreader (); <br/> (3) <br/> system. setproperty ("org. XML. sax. parser "," org. apache. xerces. parsers. saxparser "); <br/> xmlreader parser = xmlreaderfactory. createxmlreader (); <br/> (4) more directly <br/> xmlreader parser = new Org. apache. xerces. parsers. saxparser (); <br/>Translation:

In fact, xmlreader is an interface. to generate an xmlreader object, our xmlreaderfactory needs to associate a class that implements this interface. Once xmlreaderfactory obtains the name of the class that implements this interface, it creates an xmlreader object through the Java reflection mechanism and returns it to us.
In fact, org. Apache. xerces. parsers. saxparser is a class that meets these conditions.
If you want to use xmlreader parser = xmlreaderfactory. createxmlreader (string classname); To obtain an xmlreader object. xmlreaderfactory first searches for the object named "org. XML. sax. driver "attribute. If this attribute exists, an xmlreader object will be instantiated using the value of this attribute as classname. If this attribute is not set, it will jump to the parserfactory class, access a file named "org. XML. sax. parser "system variables to be instantiated; if this Org. XML. sax. if the parser variable is not set, the operation fails and runs an exception. If Org. XML. sax. if parser exists, parserfactory will return an object of a specific parser to xmlreaderfactory, and xmlreaderfactory will instantiate a paseradapter through the obtained parser object, so from the bottom layer, the obtained xmlreader object is a paseradapter object.

 

 

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.