how do I extract text from a nested xml using xmlpullparser in android?

a 夏天 提交于 2019-12-19 03:04:24

问题


<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" tags are nested inside "element"

Im using xmlpullparser in Android but I could use any other parser if it make things easier. tx.


回答1:


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();   
        }
    } 
}



回答2:


Have you had a look at the Android documentation for XMLPullParser? It pretty easy to follow. Let us know if that solves your problem.



来源:https://stackoverflow.com/questions/9469028/how-do-i-extract-text-from-a-nested-xml-using-xmlpullparser-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!