我尝试使用 XmlPullParser 解析简单的 xml 文件。
<?xml version="1.0" encoding="utf-8"?>
<tests>
<test>
<name>Jack</name>
</test>
<test>
<name>Brad</name>
</test>
<test>
<name>Tom</name>
</test>
</tests>
这是 MainActivity 代码:
public class MainActivity extends ActionBarActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
ArrayList<Quote> quotes;
ArrayList<Pers> persons;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InputStream inputStream = getResources().openRawResource(R.xml.test);
Fetcher fetcher = new Fetcher();
persons = fetcher.parse(inputStream);
String str = new String();
for(int i = 0; i < persons.size(); i++) {
str += persons.get(i).getName();
}
Log.d("1", str);
}
}
这是 Fetcher 类代码:
public class Fetcher {
private ArrayList<Pers> persons;
private Pers person;
private String text;
public Fetcher() {
persons = new ArrayList<Pers>();
}
public ArrayList<Pers> parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch(eventType) {
case XmlPullParser.START_TAG:
if(tagname.equalsIgnoreCase("test")) {
person = new Pers();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if(tagname.equalsIgnoreCase("test")) {
persons.add(person);
} else if(tagname.equalsIgnoreCase("name")) {
person.setName(text);
}
break;
default:
break;
}
eventType = parser.next();
}
} catch(XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return persons;
}
}
为什么会出现 XmlPullParserException 异常?
org.xmlpull.v1.XmlPullParserException: unterminated entity ref (position:TEXT ��������������������...@1:49 in java.io.InputStreamReader@405534d8)