The reflection mechanism is used to encapsulate the sax interpretation class to explain the XML file of the network.

Source: Internet
Author: User

The reflection mechanism is used to encapsulate the sax interpretation class to explain the XML file of the network.
I personally think that interaction with servers is essential in the Android Application development field. Generally, XML is interpreted as the main cause. In fact, retrieving XML on the network is the same as obtaining local XML, but obtaining XML on the network has an additional layer of HTTP protocol, as long as you know how to send requests and how to obtain network data, it is a good way to make a network interaction application! This is purely a personal opinion. If something is wrong, I will give it a lot ..

Well, let's get started. The following describes how to encapsulate the sax interpretation class by using the Java reflection mechanism to explain the network XML file. If the network access address is,Http: // localhost: 8080/myjsp. jspAn XML file is returned.

First, create a JavaBean class. The member attributes in this class must be consistent with the XML tag. If the returned XML file is as follows:

Create an object class. Note that the member variables are consistent with the labels. As follows:

Then, write the encapsulation class:

Import Java. io. inputstream; import Java. lang. reflect. field; import Java. lang. reflect. method; import java.net. httpurlconnection; import java.net. URL; import Java. SQL. date; import Java. util. arraylist; import Java. util. list; import javax. XML. parsers. saxparser; import javax. XML. parsers. saxparserfactory; import Org. XML. sax. attributes; import Org. XML. sax. saxexception; import Org. XML. sax. helpers. defaultha Ndler;/*** closed class ** Parse XML file using sax ** @ author administrator **/public class saxparsercontenthandler extends defaulthandler {private object JavaBean = NULL; // Tag Name: Private string tag; List <Object> List = NULL; /*** parse the XML file with Sax ** @ Param strurl * network XML address * @ Param JavaBean * Object Class Object * @ return list returns a list set of Object Classes * @ throws exception */public list <Object> parsereadxml (string strurl, object JavaBean) Throws exception {This. JavaBean = JavaBean; // to get XML from the network, define a URL-Class Object URL url = new URL (strurl); // open the connection ,. Will return the httpsurlconnection object httpurlconnection httpsurlconnection = (httpurlconnection) URL. openconnection (); // currently, HTTP is used to request server data. // you must set the Request Method httpsurlconnection. setrequestmethod ("get"); // set the timeout value to 5 seconds. setconnecttimeout (5*1000); // get the network XML content through the input stream // get the input stream inputstream = httpsurlconnection. getinputstream (); saxparserfactory parserfactory = saxparserfactory. newinstance (); // Get the saxparser instance saxparser parser = parserfactory. newsaxparser (); parser. parse (inputstream, this); return list;} @ override public void characters (char [] CH, int start, int length) throws saxexception {If (null! = Tag &&! "". Equals (TAG) {If (JavaBean! = NULL) {string data = new string (CH, start, length); field [] fields = JavaBean. getclass (). getdeclaredfields (); For (INT I = 0; I <fields. length; I ++) {If (tag. equals (fields. getname () {// system. out. println (fields. getname () + "--- fields. getname (); -- "+ fields. getType (); setattribute (JavaBean, fields. getname (), data, new class [] {fields. getType ()}) ;}}}}@ override public void endequale NT () throws saxexception {}@ override public void endelement (string Uri, string localname, string QNAME) throws saxexception {system. out. println ("endelement" + localname); If (null! = Localname &&! "". Equals (localname) {string bean = updatesmall (JavaBean. getclass (). getsimplename (); If (bean. Equals (localname) & Bean! = NULL) {list. add (JavaBean) ;}} tag = NULL ;}@ override public void startdocument () throws saxexception {// todo auto-generated method stub list = new arraylist <Object> () ;}@ override public void startelement (string Uri, string localname, string QNAME, attributes) throws saxexception {system. out. println ("startelement" + localname); tag = QNAME; // get the simple name of the object class, and change the initial letter to string bean = updatesmall (JavaBean. getclass (). getsimplename (); // system. out. println ("Bean --" + bean); // obtain the full name of the object class string clazz = JavaBean. getclass (). getname (); // system. out. println ("clazz --" + clazz); If (bean. equals (QNAME) {try {JavaBean = Class. forname (clazz ). newinstance ();} catch (exception e) {// todo auto-generated Catch Block E. printstacktrace ();} field [] fields = JavaBean. getclass (). getdeclaredfields (); For (INT I = 0; I <attributes. getlength (); I ++) {system. out. println (attributes. getqname (I) + "-- attributes --" + attributes. getvalue (I); For (Int J = 0; j <fields. length; j ++) {If (attributes. getqname (I ). equals (fields [J]. getname () {setattribute (JavaBean, attributes. getqname (I), attributes. getvalue (I), new class [] {fields [J]. getType ()}); system. out. println (fields [J]. getname () + "--- fields. getname (); -- "+ fields [J]. getType (). getname ());}}}}} /***** @ Param object * class * @ Param setname * method name * @ Param setvalue * method setting * @ Param OBJ * attribute type * @ throws exception */Public void setattribute (Object object, string setname, string setvalue, class [] OBJ) {method; try {method = object. getclass (). getmethod ("set" + updatestr (setname), OBJ [0]); If (OBJ [0]. equals (integer. class) | OBJ [0]. equals (Int. class) {method. invoke (object, new INTEGER (setvalue);} If (OBJ [0]. equals (float. class) | OBJ [0]. equals (float. class) {method. invoke (object, new float (setvalue);} If (OBJ [0]. equals (short. class) | OBJ [0]. equals (short. class) {method. invoke (object, new short (setvalue);} If (OBJ [0]. equals (byte. class) | OBJ [0]. equals (byte. class) {method. invoke (object, new byte (setvalue);} If (OBJ [0]. equals (double. class) | OBJ [0]. equals (double. class) {method. invoke (object, new double (setvalue);} If (OBJ [0]. equals (date. class) {method. invoke (object, new date (New Long (setvalue);} If (OBJ [0]. equals (Java. util. date. class) {method. invoke (object, new Java. util. date (setvalue);} If (OBJ [0]. equals (Long. class) | OBJ [0]. equals (Long. class) {method. invoke (object, new long (setvalue);} If (OBJ [0]. equals (Boolean. class) | OBJ [0]. equals (Boolean. class) {method. invoke (object, new Boolean (setvalue);} If (OBJ [0]. equals (string. class) {method. invoke (object, setvalue) ;}} catch (exception e) {// todo auto-generated Catch Block E. printstacktrace () ;}}/*** change the first letter of the string to uppercase ** @ Param Str *: * @ return string */Public String updatestr (string Str) {char c = (char) (Str. charat (0)-32); string S = Str. substring (1, str. length (); Return C + S;}/*** change the first letter of the string to lowercase ** @ Param Str *: * @ return string */Public String updatesmall (string Str) {char c = (char) (Str. charat (0) + 32); string S = Str. substring (1, str. length (); Return C + S ;}}

The preceding encapsulation class has been annotated in detail, and finally how to get the desired data.

1: instantiate an object class
2: instantiate the encapsulation class
3: add the instantiation class to the contenthandler. parsereadxml method, as shown below:

 
Saxparsercontenthandler contenthandler = new saxparsercontenthandler (); video Video = new video (); List <Object> List = contenthandler. parsereadxml ("http://0029.freejsp.net/0105/MyJsp.jsp", video); For (Object object: List) {Video = (video) object; system. out. println (video );}

Finally, traverse the list set to get the data you want. In my opinion, this is much more convenient, and there is no need to compare tags one by one, saving a lot of time.

 Welcome to andriod development and love to join the group for communication and make common progress. Xi'an group 252746034 Beijing group 111059554 Shenzhen group 252742753

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.