本文介绍了如何在android中使用xmlpullparser从嵌套的xml中提取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<doc>
<element>
text
<item>
text1
</item>
<item>
text2
</item>
text3
</element>
<element>
another text
</element>
...
</doc>
我想将文本提取为这样的字符串:
And I want to extract text to an string like this:
"text text1 text2 text3"
item"标签嵌套在element"内
"item" tags are nested inside "element"
我在 Android 中使用 xmlpullparser,但如果它使事情变得更容易,我可以使用任何其他解析器.tx.
Im using xmlpullparser in Android but I could use any other parser if it make things easier.tx.
推荐答案
我解析了类似的 xml 文件.这是一个例子.您需要根据需要添加错误检查.
I parse similar xml files. Here is an example. You'll need to add error checking as appropriate.
void loadXML(XmlPullParser xpp) {
int eventType = xpp.next();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG && 0 == XML_ELEMENT_TAG.compareTo(xpp.getName())) {
loadElement(xpp);
}
eventType = xpp.next();
}
}
private void loadElement(XmlPullParser xpp) {
int eventType = xpp.getEventType();
if ( eventType == XmlPullParser.START_TAG && 0 == XML_ELEMENT_TAG.compareTo(xpp.getName()) ) {
eventType = xpp.next();
while ( eventType != XmlPullParser.END_TAG || 0 != XML_ELEMENT_TAG.compareTo(xpp.getName()) ) {
if (eventType == XmlPullParser.START_TAG && 0 == XML_ITEM_TAG.compareTo(xpp.getName())) {
loadItem(xpp);
}
eventType = xpp.next();
}
}
}
private void loadItem(XmlPullParser xpp) {
int eventType = xpp.getEventType();
if ( eventType == XmlPullParser.START_TAG && 0 == XML_ITEM_TAG.compareTo(xpp.getName()) ) {
eventType = xpp.next();
while ( eventType != XmlPullParser.END_TAG || 0 != XML_ITEM_TAG.compareTo(xpp.getName()) ) {
// Get attributes.
String attr = xpp.getAttributeValue(null, XML_MY_ATTR);
String text = null;
// Get item text if present.
eventType = xpp.next();
while ( eventType != XmlPullParser.END_TAG || 0 != XML_ITEM_TAG.compareTo(xpp.getName()) ) {
if ( eventType == XmlPullParser.TEXT ) {
text = xpp.getText();
}
eventType = xpp.next();
}
eventType = xpp.next();
}
}
}
这篇关于如何在android中使用xmlpullparser从嵌套的xml中提取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!