Java xml Parsing For Two Tags with Same Name -


i writing code parse xml file. want retrieve country tag values , save string[]. when trying do, retrieving 1 value. have country tag repeated twice in xml. in future can thrice or 4 times , on dynamic. xml:

<?xml version="1.0"?> <metadata> <country>all countries</country> <country>us - united states</country> </metadata> 

this code:

private static string parsexml(string xmldata)         throws parserconfigurationexception, saxexception, ioexception {     documentbuilder builder = documentbuilderfactory.newinstance()             .newdocumentbuilder();     inputsource src = new inputsource();     src.setcharacterstream(new stringreader(xmldata));     document doc = builder.parse(src);     nodelist nodes = doc.getelementsbytagname("metadata");     element line = null;     string cnt = null;     (int = 0; < nodes.getlength(); i++) {         element element = (element) nodes.item(i);         nodelist country = element.getelementsbytagname("country");         (int j = 0; j < country.getlength(); j++) {             if (country != null) {                 system.out.println("country not null " + country);                 line = (element) country.item(0);                 if (line != null) {                     cnt = getcharacterdatafromelement(line);                 }             }         }     }     return cnt;  }  public static string getcharacterdatafromelement(element e) {     node child = e.getfirstchild();     if (child instanceof characterdata) {         characterdata cd = (characterdata) child;         if (cd != null) {             return cd.getdata();         }     }     return ""; } 

your code not provide possibility store list of countries in code, although iterates on countries.

the following should (although untested): change string cnt = null; list<string> = new arraylist<string>() , instead of

for (int j = 0; j < country.getlength(); j++) {     if (country != null) {         system.out.println("country not null " + country);         line = (element) country.item(0);         if (line != null) {             cnt = getcharacterdatafromelement(line);         }     } } 

the following:

if (country != null) {     system.out.println("country not null " + country);     (int j = 0; j < country.getlength(); j++) {         line = (element) country.item(j);         if (line != null) {             cnt.add( getcharacterdatafromelement(line));         }     } } 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -