bak 6.android xml解析 XmlPullParser的使用.

android xml 的解析.

1.普通型

<?xml version=”1.0″ ?>
<statuses>
<status>
<source1>a</source1>
<source2>a</source2>
<source2>a</source2>
</status>
<statuses>
</xml>
解析代码.
try{
xpp.setInput( new StringReader ( “xml string” ) );
XmlPullParser parser = XmlPullParserFactory.newInstance()
.newPullParser();
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String name = parser.getName();
Log.v(“tag”,parser.getName()+”=”+parser.next());
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
} catch (Exception e) {
}
2.嵌套子类.
<?xml version=”1.0″ encoding=”UTF-8″ standalone=”no”?>
<statuses>
<status>
 <source1>a</source1>
 <source2>a</source2>
 <source2>a</source2>
 <user>
   <source1>a</source1>
   <source2>a</source2>
   <source2>a</source2>
 </user>
</status>
<status>
 <source1>a</source1>
 <source2>a</source2>
 <source2>a</source2>
 <user>
   <source1>a</source1>
   <source2>a</source2>
   <source2>a</source2>
 </user>
</status>
<statuses>
</xml>
解析代码:
try{
XmlPullParser parser = XmlPullParserFactory.newInstance()
.newPullParser();
 xpp.setInput( new StringReader ( xml string ) );
parser.next();
parser.require(XmlPullParser.START_TAG, null, “statuses”);
while (parser.nextTag() != XmlPullParser.END_TAG) {
parser.require(XmlPullParser.START_TAG, null, “status”);
for (int i=0;i<3;i++){
parser.nextTag();
Log.v(“tag”,parser.getName()+”=”+ parser.nextText());
}
while (parser.nextTag() != XmlPullParser.END_TAG) {
parser.require(XmlPullParser.START_TAG, null, “user”);
while (parser.nextTag() != XmlPullParser.END_TAG) {
String name = parser.getName();
String text2 = parser.nextText();
Log.v(“tag”,”text2″+text2);
parser.require(XmlPullParser.END_TAG, null, name);
}
parser.require(XmlPullParser.END_TAG, null, “user”);
}
parser.require(XmlPullParser.END_TAG, null, “status”);
}
parser.require(XmlPullParser.END_TAG, null, “statuses”);
parser.next();
parser.require(XmlPullParser.END_DOCUMENT, null, null);
// global.userinfo.dump();
} catch (XmlPullParserException e) {
} catch (Exception e) {
}
最里面那个可以满足 <user>也是循环. 如果<user>不循环.
可以使用.
for (int i=0;i<3;i++){
parser.nextTag();
Log.v(“tag”,parser.getName()+”=”+ parser.nextText());
}
代替.

你可能感兴趣的:(exception,xml,String,user,null,encoding)