这是正确的程序,现在正常运行:)谢谢先生
我是Android新手。我有一个String,它包含服务器返回给我的XML格式数据(它是一个XML文档)。我想在Android中使用XmlResourceParser
解析它,但它只接受存储在您设备上的xml文档,例如:
XmlResourceParser xmlResourceParser = getResources().getXml(
R.xml.new_xml);
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<ItemInfo>" + "<Status>Success</Status>"
+ "<Reason></Reason>" + "<IsMore>yes</IsMore>"
+ "<ItemList>"
+ "<Item Name=\"Ahmad\" Level=\"1\" UserId=\"5\"></Item >"
+ "<Item Name=\"Ahmad\" Level=\"1\" UserId=\"5\"></Item >"
+ "<Item Name=\"Ahmad\" Level=\"1\"UserId=\"5\"></Item >"
+ "</ItemList>" + "</ItemInfo>";
我希望XmlResourceParser解析我的这个字符串。但是如何让它接受这个字符串作为xml文档。 使用以下方法但是装箱异常
private XmlPullParser xmlResourceParser;
xml = xml.replaceAll("\t", "");
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
xmlResourceParser = factory.newPullParser();
xmlResourceParser.setInput(new StringReader(xml));
} catch (Exception ex) {
ex.printStackTrace();
}
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
try {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = xmlResourceParser.getName();
if (strNode.equalsIgnoreCase("Status")) {
do {
xmlResourceParser.next();
} while (eventType == XmlResourceParser.TEXT);
if (!xmlResourceParser.getText().equalsIgnoreCase(
"success")) {
do {
eventType = xmlResourceParser.next();
} while (eventType != XmlResourceParser.START_TAG);
if (xmlResourceParser.getName().equalsIgnoreCase(
"reason"))
eventType = xmlResourceParser.next();
todoItems.add(xmlResourceParser.getText());
return todoItems;
}
}
if (strNode.equals("IsMore")) {
do {
xmlResourceParser.next();
} while (eventType == XmlResourceParser.TEXT);
if (xmlResourceParser.getText().equalsIgnoreCase("yes"))
todoItems.add("nextPage");// if nextPage then there
// is one more page
// otherwise no next
// page
else
todoItems.add("lastPage");// show user pervious
// button instead of
// next button
}
if (strNode.equals("Item")) {
todoItems.add(xmlResourceParser.getAttributeValue(null,
"Name"));
todoItems.add(xmlResourceParser.getAttributeValue(null,
"Level"));
todoItems.add(xmlResourceParser.getAttributeValue(null,
"UserId"));
}
}
eventType = xmlResourceParser.next();
} catch (XmlPullParserException xmlPullExp) {
xmlPullExp.printStackTrace();
todoItems.add("XmlPullParserException");
} catch (IOException ioExp) {
ioExp.printStackTrace();
todoItems.add("IOException");
} catch (Exception exp) {
exp.printStackTrace();
todoItems.add("Exception");
}
}
return todoItems;
}
答案 0 :(得分:4)
尝试使用XmlPullParser
http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
例如:
InputStream xmlIS;
.....
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(xmlIS, null);