android general xml parsing method

  • 2020-05-09 19:20:52
  • OfStack

1. Why write a generic xml parsing method?

When different xml nodes need to be parsed. You may be matching different nodes when xml is parsing and the node names are all dead, so you need different parsing methods to parse different nodes. This is, of course, the easiest and dumbest way to do it. In order to reduce the code and make it more quality you need to consider designing a generic xml parsing method.

2. Analytical thinking.

In general, xml's parsing results are best placed in an entity class object, which is very convenient for you to use (OO, of course). You can also choose other methods to save the parsing results, but I think this method is better. What do you need to do in the parsing process? This is the key to parsing. In fact, the result to be resolved is set to the properties of the object (member variables). Considering this, it is necessary to know what properties the object has, so add a method to the entity class to obtain the properties. The next step after you know the property names is of course to set the values of those properties. Because different entity classes have different properties, reflection is used to set the value. So that's the general idea. We'll talk about that later.

3. Parse the format type of xml.

The text only writes two xml parses. You can use the ideas in this article for other formats.

Only nodes in the content: such as


<?xml version="1.0" encoding="UTF-8" ?>
<Result>
  <StuId>30323</StuId>
  <ClassID>10042</ClassID>
</Result>

Only node properties: such as


<?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 it.

According to the design idea, you need 1 entity class, but the entity class has 1 specification (for analysis). So these specifications need to implement some unified methods, so you have an abstract class: BaseObj.


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();
}
}
}

(2) generate class members according to the specific node type. Here's the xml that needs to be parsed.


<?xml version="1.0" encoding="UTF-8" ?> 
  <DsXml>
  <IsLog>true</IsLog> 
  <GradeID>10001</GradeID> 
  <GradeName> high 1 grade </GradeName> 
  <ClassID>10010</ClassID> 
  <ClassName> high 1(01) class </ClassName> 
  <UserID>10000</UserID> 
  <UserName> zhang 3</UserName> 
  </DsXml>

(3) the corresponding entity class.


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" };
}
}

The specification in the entity class is this: getNodes() returns the node name of xml, the name must be the same, and the member variable name must be the same as the node name. Of course, implementing the Serializable interface here is just a requirement in my own project, not related to this article.

The most important is how to analyze.


View Code 
/**
 * @description : Parses the contents of a node, encapsulating it as 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 done when the class is initialized. 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 it is as follows:


XmlUtils.streamText2Model(result, ActMain.student);

Simple enough. result is the data flow of xml. Specific detail can oneself experience 1. This parse class is generic to a certain extent, meaning that your xml format is "node-only." This type of xml is referred to as "type A" for the sake of explanation below.

Talk about another format "only node attributes" how to "generic" parsing. This type of xml is referred to as "type B" for the convenience of the following instructions. The code for type B is covered below. The xml of type B is as follows:


View Code 
 <?xml version="1.0" encoding="UTF-8" ?> 
  <DsXml>
  <ProjLst KeliName=" test 1" KeliId="170" SubId="13" ExeTp="1" ExeType=" preview " ExeDt="2013-2-27" ExeCount="4" SubName=" Information technology (it) " /> 
  <ProjLst KeliName=" test 2" KeliId="154" SubId="13" ExeTp="1" ExeType=" preview " ExeDt="2012-11-19" ExeCount="2" SubName=" Information technology (it) " /> 
  <ProjLst KeliName=" test 2" KeliId="150" SubId="13" ExeTp="3" ExeType=" After class, " ExeDt="2012-11-15" ExeCount="2" SubName=" Information technology (it) " /> 
  </DsXml>

The entity class of type B is as follows :(actually, it is the same as type A)


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" };
}
}

(8) type B


<?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>
0
9. How to use the resolution of the category B.


ArrayList<TmInfo>  datas = (ArrayList<TmInfo>) XmlUtils.stream2Tm(result, new TmInfo());

Summary: although only these two types are written here, a more complex xml parsing can be done according to this reflection mechanism. Always pay attention to the specification of variable naming when using 1. The code is much more elegant when parsed this way, and xml parses it according to your variables, rather than writing it to death.

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


Related articles: