XML
<foo>text</foo>
从http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html复制的解析器代码
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
pullParserFactory.setNamespaceAware(true);
mParser = pullParserFactory.newPullParser();
InputStream inputStream = getResources().openRawResource(R.xml.foo);
mParser.setInput(inputStream, null);
//mParser.setInput(new StringReader("<foo>text</foo>"));
int eventType = mParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+mParser.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+mParser.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+mParser.getText());
}
eventType = mParser.next();
}
System.out.println("End document");
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
它在第一次调用 next() 时生成以下错误,但仅在使用 setInput(InputStream, encoding) 时。该示例使用 setInput(StringReader) 在您使用该版本的 setInput 时可以正常工作;
06-07 12:35:30.992: W/System.err(30950): org.xmlpull.v1.XmlPullParserException: 意外令牌(位置:TEXT ��������������4�� ����...@1:149 在 java.io.InputStreamReader@425ceab0)