androidxmlxml-parsingandroid-xmlpullparser

Parse all XML text using XMLPullParser


I have a question that is similar to [this one here][1] I have read tutorials about XMLPullParser and do not seem to get this one.

I have an XML tag I want to parse using XMLPullParser

<dt>
: <sx>outcome</sx>
<sx>result</sx>
</dt>

I want to get the result ": outcome result." Because I am reading this XML from an online base. It may change. For instance :

<dt>
:degree or measure of
<d_link>succeeding</d_link>
</dt>

The question is how do I parse and get all the text in the tag "dt" irrespective of the name of the tags in it?

This is what I have tried but it is not working.

while (parser.next() != END_TAG){
            if (parser.getEventType() != TEXT)
            {
                continue;
            }
            else if (parser.getEventType() == TEXT)
            {
                Log.d("Text", parser.getText()+" in the likelihood");
                stringBuilder.append(parser.getText());
                parser.next();
            }

            }

Solution

  • You should do something similar to:

    while (eventType != XmlPullParser.END_DOCUMENT) 
    {
        String tagname = parser.getName();
        switch (eventType) 
        {
            case XmlPullParser.START_TAG:
                if (tagname.equalsIgnoreCase("dt")) 
                {
                     // create a new instance of DTClass
                     dt= new DTClass();
                }
                break;
    
            case XmlPullParser.TEXT:
                 text = parser.getText();
                 break;
    
             case XmlPullParser.END_TAG:
                 if (tagname.equalsIgnoreCase("dt")) {
                      // add DTClass object to list
                      dts.add(dt);
                 } 
                 else if (tagname.equalsIgnoreCase("sx")) 
                 {
                      dt.setSX(text);
                 } 
    
                 break;
    
             default:
                 break;
         }
         eventType = parser.next();
    }