Android Common XML parsing method _android

Source: Internet
Author: User
Tags gettext object model reflection

1. Why do I need to write a general XML parsing method.

When you need to parse a different XML node. You might be able to match different nodes in XML parsing, and the node names are written to death, so you need different parsing methods to parse different nodes. Of course this is the simplest and the most stupid way. To reduce the code to write more quality code, you need to consider designing a common XML parsing method.

2, analytical thinking.

In general, XML parsing results are best placed in an entity class object, which makes it easy to use (and more oo), and you can choose other methods to save the results, but personally feel that this is a better way. What do you need to do in the parsing process? This is the key to parsing. In fact, to set the result of the resolution to the object's properties (member variables), in consideration of this, it must be necessary to know what attributes of the object Ah, then add a method to the entity class (in fact, this is to do a certain specification) to obtain attributes. When you know the property name, the next step, of course, is to set the values of these properties. Because the properties of different entity classes are different, the setting values are based on the reflection mechanism. The general idea is this way. The concrete code says later.

3. Parse the format type of XML.

Text writes only two XML-formatted parsing. Other formats you can refer to the idea of this article are free to play.

① only the contents of the node:

Copy Code code as follows:

<?xml version= "1.0" encoding= "UTF-8"?>

<Result>

<StuId>30323</StuId>

<ClassID>10042</ClassID>

</Result>


② only node properties: such as

Copy Code code as follows:

<?xml version= "1.0" encoding= "UTF-8"?>

<Result>

<projlst name= "Test 1" id= "1"/>

<projlst name= "Test 2" id= "2"/>

<projlst name= "Test 3" id= "3"/>

</Result>


4, how to achieve.

① According to the design idea, you need an entity class, but the entity class has a certain specification (for parsing). So these specifications also need to implement a number of unified methods, so there is an abstract class: Baseobj.

Copy Code code as follows:

Baseobj

/***********************************************************

* @description: This class function is TODO

*

* @create Author:kwzhang

* @create date:2013-2-28

* @modify Author:

* @modify Date:

* @contact: vanezkw@163.com

*

**********************************************************/

Package Com.vane.elearning.model;

Import Java.lang.reflect.Field;

/**

* @author Kwzhang

*

*/

Public abstract class Baseobj {

Public abstract string[] Getnodes ();

public void Setparamater (String tag, Object value) {

try {

Field field = GetClass (). GetField (tag);

Field.setaccessible (TRUE);

Field.set (this, value);

catch (SecurityException e) {

E.printstacktrace ();

catch (Nosuchfieldexception e) {

E.printstacktrace ();

catch (IllegalArgumentException e) {

E.printstacktrace ();

catch (Illegalaccessexception e) {

E.printstacktrace ();

}

}

}


② generates the members of a class based on the specific node type. Let's look at the XML to parse first.

Copy Code code as follows:

<?xml version= "1.0" encoding= "UTF-8"?>

<DsXml>

<IsLog>true</IsLog>

<GradeID>10001</GradeID>

<GradeName> Grade </GradeName>

<ClassID>10010</ClassID>

<ClassName> (01) class </ClassName>

<UserID>10000</UserID>

<UserName> John </UserName>

</DsXml>


③ the corresponding entity class.

Copy Code code as follows:

View Code

/***********************************************************

* @description: This class function is TODO

*

* @create Author:kwzhang

* @create date:2013-2-28

* @modify Author:

* @modify Date:

* @contact: vanezkw@163.com

*

**********************************************************/

Package Com.vane.elearning.model;

Import java.io.Serializable;

/**

* @author Kwzhang

*

*/

public class Student extends Baseobj implements Serializable {

Private static final long serialversionuid = 1L;

Public String Gradeid, Gradename, ClassID, ClassName, UserID, UserName;

Public Student () {

}

@Override

Public string[] Getnodes () {

return new string[] {"Gradeid", "Gradename", "ClassID", "ClassName", "UserID", "UserName"};

}

}


This specification is in the entity class: Getnodes () returns the node name of the XML, the name must be the same, and the member variable names must be the same as the section names. Of course, the implementation of the serializable interface is only a requirement in my own project, and it has nothing to do with this article.

The key to ④ is how to parse.

Copy Code code as follows:

View Code

/**

* @description: Parsing the contents of the node and encapsulating it into an object model.

* @author: Kwzhang

* @create: 2013-2-28

* @param in

* @param obj

* @throws Exception

* @return: void

*/

public static <t extends baseobj> void Streamtext2model (InputStream in, T obj) throws Exception {

Pullparser.setinput (in, encode);

int eventtype = Pullparser.geteventtype ();

string[] nodes = Obj.getnodes ();

String nodename = null;

Boolean success = true;

while (EventType!= xmlpullparser.end_document && success) {

Switch (eventtype) {

Case Xmlpullparser.start_document:

Break

Case Xmlpullparser.start_tag:

NodeName = Pullparser.getname ();

Break

Case Xmlpullparser.text:

if ("Islog". Equals (nodename) && pullparser.gettext (). Equals ("false")) {

Success = false;

Break

}

for (int i = 0; i < nodes.length; i++) {

if (Nodes[i].equals (nodename)) {

Obj.setparamater (NodeName, Pullparser.gettext ());

}

}

Break

Case Xmlpullparser.end_tag:

Break

}

EventType = Pullparser.next ();

}

}


Of course, some of the variables are completed when the class is initialized. As follows:

Copy Code code as follows:

private static String encode = "Utf-8";

public static Xmlpullparser Pullparser;

static {

try {

Pullparser = Xmlpullparserfactory.newinstance (). Newpullparser ();

catch (Xmlpullparserexception e) {

E.printstacktrace ();

}

}


⑤ how to use. as follows:

Copy Code code as follows:

Xmlutils.streamtext2model (result, actmain.student);

It's very simple. Result is the data flow of XML. Specific details can be realized by yourself. This analytic class can be generalized to some extent, that is, your XML format conforms to the "only node content" so that it can be so generic. This type of XML is called "Type a" for the convenience of the following instructions.

⑥ said another format "only node properties" How to "general" resolution. This type of XML is referred to as "Type B" for the purposes of the following instructions. The following are all the related code for type B. The XML for Type B is as follows:

Copy Code code as follows:

View Code

<?xml version= "1.0" encoding= "UTF-8"?>

<DsXml>

<projlst keliname= "Test 1" keliid= "170" subid= "exetp=" 1 "exetype=" Preview "exedt=" 2013-2-27 "execount=" 4 "subname=" Information technology "/>

<projlst keliname= "Test 2" keliid= "154" subid= "exetp=" 1 "exetype=" Preview "exedt=" 2012-11-19 "execount=" 2 "SubName=" Information Technology "/>

<projlst keliname= "Test 2" keliid= "subid=" "exetp=" 3 "exetype=" after Class "exedt=" 2012-11-15 "execount=" 2 "subname=" Information Technology "/>

</DsXml>


The ⑦ Type B entity class is as follows: (in fact, type A is the same)

Copy Code code as follows:

View Code

/***********************************************************

* @description: This class function is TODO

*

* @create Author:kwzhang

* @create date:2013-2-28

* @modify Author:

* @modify Date:

* @contact: vanezkw@163.com

*

**********************************************************/

Package Com.vane.elearning.model;

Import java.io.Serializable;

/**

* @author Kwzhang

*

*/

public class Keli extends Baseobj implements Serializable {

Private static final long serialversionuid = 1L;

Public String Keliname, Keliid, SubId, Exetp, Exetype, Exedt, Execount, subname;

Public Keli () {

}

@Override

Public string[] Getnodes () {

return new string[] {"Keliname", "Keliid", "SubId", "Exetp", "Exetype", "Exedt", "Execount", "SubName"};

}

}


The ⑧ Type B parsing method is as follows:

Copy Code code as follows:

View Code

/**

* @description: Parses the attributes in the XML and encapsulates them into an object model.

* @author: Kwzhang

* @create: 2013-2-28

* @param in

* @param obj

* @throws Exception

* @return: void

*/

public static <t extends baseobj> list<t> Streamparam2model (inputstream in, T obj) throws Exception {

Pullparser.setinput (in, encode);

int eventtype = Pullparser.geteventtype ();

arraylist<t> list = new arraylist<t> (4);

string[] nodes = Obj.getnodes ();

while (EventType!= xmlpullparser.end_document) {

Switch (eventtype) {

Case Xmlpullparser.start_document:

Break

Case Xmlpullparser.start_tag:

String name = Pullparser.getname ();

Boolean flag = false;

if (null = = Name | | name.equals ("")) {

Break

}

for (int i = 0; i < nodes.length; i++) {

String value = Pullparser.getattributevalue (null, nodes[i]);

Flag |= (null!= value);

Obj.setparamater (Nodes[i], value);

}

if (flag) {

List.add (obj);

}

Constructor<t> constructor = (constructor<t>) obj.getclass (). GetConstructor ();

obj = Constructor.newinstance ();

Break

Case Xmlpullparser.end_tag:

Break

}

EventType = Pullparser.next ();

}

return list;

}


⑨ How to use the parsing of Class B.

Copy Code code as follows:

arraylist<tminfo> datas = (arraylist<tminfo>) xmlutils.stream2tm (result, new Tminfo ());

Summary: Although there are only two types written here, more complex XML parsing can be done based on this reflection mechanism. You must pay attention to the specification of variable naming when you use it. In this way, the code design is more elegant, and the XML parsing will be based on your variables to parse, rather than write dead.

Reprinted from: http://www.cnblogs.com/vanezkw/archive/2013/03/03/2941496.html

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.