0

I am getting an XML text from a web service. I have successfully loaded the stream XmlPullParser object by getting parser.setInput(con.getInputStream(),null); where parser is my XmlPullParser object and con is my connection to the URL.

I am reading the stream but I don't know how to get specific parts to it. This is how the XML file looks like:

    `<response> 
<list><category>(noun)</category><synonyms>order|war (antonym)</synonyms></list> 
<list><category>(noun)</category><synonyms>harmony|concord|concordance</synonyms></list> 
<list><category>(noun)</category><synonyms>public security|security</synonyms></list> 
<list><category>(noun)</category><synonyms>peace treaty|pacification|treaty|pact|accord</synonyms></list> 
</response>`

I would like access the text within in the <synonyms> tags but not sure how to do that. This is what I have:

int eventType = parser.getEventType();
        while(eventType != XmlPullParser.END_DOCUMENT){
            String name = parser.getName();
            if(eventType == XmlPullParser.TEXT) {

                stringToBeDisplayed.add(parser.getText()+"\n");
            }
            eventType = parser.next();
        }

But the above code gets the Text within the <category> tag and the <synonyms> which I dont want. I only want the text enclosed in the <synonyms> tag.

2 Answers2

2

Do something like this

String tagValue = null, tagName = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
      switch (eventType) {
          case XmlPullParser.TEXT:
               tagValue = xmlPullParser.getText();
               break;
          case XmlPullParser.END_TAG:
               tagName = xmlPullParser.getName();
               if (tagName != null && tagName.toUpperCase().equals("SYNONYMS")) {
                        // do something with tagValue
                        stringToBeDisplayed.add(tagValue);
               } 
               break;
        }
}
Puneet Arora
  • 199
  • 7
  • Thanks for that. It works. Can you tell me in my code why a blank value comes into my stringToBeDisplayed List since I dont understand why I am getting a blank string after – Tarikh Chouhan Mar 17 '16 at 21:49
  • btw why are you doing this +"\n"? just do stringToBeDisplayed.add(tagValue).. edited my answer. Please accept if you think it works. – Puneet Arora Mar 17 '16 at 21:51
  • Best one that I've searched In google about my issue, tnx. Why don't accepted like best answer? – Alexander Vasilchuk Apr 02 '19 at 21:24
0

You have to implement a SAX XML Parser and Handler.

If you search on google there are thousands of tutorials. Here's one. And here there is an explanation between two different SAX implementations: the org.xml.sax or the android.sax and explain pro's and con's of both with examples

Community
  • 1
  • 1
Automatik
  • 329
  • 1
  • 7
  • 15