user3260664
user3260664

Reputation: 155

How to extract all text form specific tag of xml on android

Lets say I have .xml file containing

<?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>

and i want to extract all text from element tag, so in result i want to get "text 1 text 2 text 3 text 4". how can i do that?

Upvotes: 0

Views: 671

Answers (1)

Raghunandan
Raghunandan

Reputation: 133560

You can use a XmlPullParser to parse the xml.

You can find more information @

http://developer.android.com/training/basics/network-ops/xml.html

To invoke

new XMLPullParserHandler().parse(your input stream);

Then

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

The log

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

You can use Dom parser, Sax parser as well.

Upvotes: 1

Related Questions