假设我有包含
的.xml文件<?xml version="1.0" encoding="UTF-8"?>
<root>
<element>
<item>
<p>text 1</p>
<p>text 2</p>
</item>
<item>
<p>text 3</p>
<p>text 4</p>
</item>
</element>
</root>
我希望从元素标签中提取所有文本,因此在结果中我想得到“text 1 text 2 text 3 text 4”。我怎么能这样做?
答案 0 :(得分:1)
您可以使用XmlPullParser
来解析xml。
您可以找到更多信息@
http://developer.android.com/training/basics/network-ops/xml.html
调用
new XMLPullParserHandler().parse(your input stream);
然后
public class XMLPullParserHandler {
private String text;
public XMLPullParserHandler() {
}
public Void parse(InputStream is) { // input stream
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
//factory instantiates an object
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
String val = null;
if (tagname.equalsIgnoreCase("p")) { // tag p
val=text; // get the text
Log.i(""," text is "+val);
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
日志
04-24 10:01:19.236: I/(1662): text is text 1
04-24 10:01:19.236: I/(1662): text is text 2
04-24 10:01:19.246: I/(1662): text is text 3
04-24 10:01:19.256: I/(1662): text is text 4
您也可以使用Dom解析器,Sax解析器。