0

I am struggling from many hours to parse some XMl data.

XML Data:

 <?xml version="1.0" encoding="utf-8"?>
 <data>
 <status>200</status>
<description>OK</description>

<topcities>
       <city>Ahmedabad</city>
       <city>Bangalore</city>
       <city>Chandigarh</city>
       <city>Chennai</city>
       <city>Cochin</city>
       <city>Faridabad</city>
       <city>Ghaziabad</city>
       <city>Gurgaon</city>
       <city>Hyderabad</city>
       <city>Kolkata</city>
       <city>Mumbai</city>
       <city>Navi Mumbai</city>
       <city>New Delhi</city>
       <city>Noida</city>
       <city>Pune</city>
       <city>Thane</city>
</topcities>
<othercities>
       <city>Agra</city>
       <city>Ahmednagar</city>
       <city>Ajmer</city>
       <city>Akola</city>
       <city>Allahabad</city>
       <city>Ambala</city>
       <city>Amravati</city>
       <city>Amritsar</city>
       <city>Anand</city>
       <city>Aurangabad</city>
       <city>Belgaum</city>
       <city>Bharuch</city>
       <city>Bhavnagar</city>
       <city>Bhilai</city>
       <city>Bhopal</city>
       <city>Bhubaneswar</city>
       <city>Bhuj</city>
       <city>Bilaspur</city>
       <city>Coimbatore</city>
       <city>Dehradun</city>
       <city>Dhanbad</city>
       <city>Dharwad</city>
       <city>Durgapur</city>
       <city>Durg</city>
       <city>Erode</city>
       <city>Firozabad</city>
       <city>Gandhidham</city>
       <city>Gandhinagar</city>
       <city>Goa</city>
       <city>Guwahati</city>
       <city>Gwalior</city>
       <city>Haldwani</city>
       <city>Himmatnagar</city>
       <city>Howrah</city>
       <city>Hubli</city>
       <city>Indore</city>
       <city>Jabalpur</city>
       <city>Jaipur</city>
       <city>Jalandhar</city>
       <city>Jamnagar</city>
       <city>Jamshedpur</city>
       <city>Jodhpur</city>
       <city>Kanpur</city>
       <city>Kolhapur</city>
       <city>Kollam</city>
       <city>Kota</city>
       <city>Kottayam</city>
       <city>Kozhikode</city>
       <city>Kurukshetra</city>
       <city>Lucknow</city>
       <city>Ludhiana</city>
       <city>Madurai</city>
       <city>Mangalore</city>
       <city>Mathura</city>
       <city>Meerut</city>
       <city>Mehsana</city>
       <city>Mohali</city>
       <city>Mysore</city>
       <city>Nagpur</city>
       <city>Nanded</city>
       <city>Nashik</city>
       <city>Nellore</city>
       <city>Panchkula</city>
       <city>Panipat</city>
       <city>Patiala</city>
       <city>Patna</city>
       <city>Pondicherry</city>
       <city>Raipur</city>
       <city>Rajkot</city>
       <city>Ranchi</city>
       <city>Ratnagiri</city>
       <city>Rohtak</city>
       <city>Saharanpur</city>
       <city>Salem</city>
       <city>Sangli</city>
       <city>Satara</city>
       <city>Shimla</city>
       <city>Shillong</city>
       <city>Siliguri</city>
       <city>Sivakasi</city>
       <city>Solapur</city>
       <city>Srinagar</city>
       <city>Surat</city>
       <city>Thanjavur</city>
       <city>Thrissur</city>
       <city>Tirunelveli</city>
       <city>Tirupati</city>
       <city>Tirupur</city>
       <city>Trichy</city>
       <city>Trivandrum</city>
       <city>Udaipur</city>
       <city>Ujjain</city>
       <city>Vadodara</city>
       <city>Vapi</city>
       <city>Valsad</city>
       <city>Varanasi</city>
       <city>Vellore</city>
       <city>Vijayawada</city>
       <city>Visakhapatnam</city>
       <city>Visnagar</city>
       <city>Warangal</city>
       <city>Yamunanagar</city>
 </othercities>
 </data>

My Parsing Code:

   XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL);
       // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_TOP_CITY);

        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            //HashMap<String, String> map = new HashMap<String, String>();

            Element e = (Element) nl.item(i);
            NodeList children = e.getChildNodes();

              for (int j = 0; j < children.getLength(); j++) {
                  Node child = children.item(j);
                    HashMap<String, String> map = new HashMap<String, String>();
                    if (child.getNodeName().equalsIgnoreCase(KEY_CITY)) {
                        Log.v("Data", parser.getValue(e, KEY_CITY));
                        map.put(KEY_CITY, parser.getValue(e, KEY_CITY));
                     }

                    menuItems.add(map);
                }

But unfortunately I am getting only the first city(Ahmedabad) repeatedly. But I want all cities to show..

Can anyone please help ..

Thanks ..

2 Answers 2

1

Here's another implementation using the org.w3c.dom package. This code loads from a local file, but you could easily modify it to use a URL.

try
    {
        Document document =  DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("test.xml"));
        document.getDocumentElement().normalize();

        System.out.println("Root element: " + document.getDocumentElement().getNodeName());

        NodeList nodeList = document.getElementsByTagName("topcities");

        System.out.println("-------------------------------");

        for (int i=0; i<nodeList.getLength();i++)
        {
            Node node = nodeList.item(i);
            System.out.println("Current Element: " + node.getNodeName());

            if (node.getNodeType() == Node.ELEMENT_NODE)
            {
                // You would put your code to add the city to the map in place
                // of the print statement.
                System.out.println(node.getTextContent());
            }
        }
    }
    catch (SAXException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    catch (ParserConfigurationException e)
    {
        e.printStackTrace();
    }

By the way, that second for loop is redundant (unless the city element can have children.) You just need to loop through the list that you retrieved via getElementsByTagName.

Sign up to request clarification or add additional context in comments.

2 Comments

a little change I have made for getting all cities...from getElementsByTagName("topcities") to getElementsByTagName("city")..
0

Try this code.. The xml pull parser is better than other xml parsers

  XmlPullParserFactory pullParserFactory;
        try {
            pullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = pullParserFactory.newPullParser();


            String file = "assets/name of your xml file";
            InputStream in_s = this.getClass().getClassLoader().getResourceAsStream(file);

            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in_s, null);

            parseXML(parser);



        } catch (XmlPullParserException e) {

        } catch (IOException e) {

        }




        private void parseXML(XmlPullParser parser) throws XmlPullParserException,
            IOException {


        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String cityName = null;


            cityName = parser.getName();


                    if(eventType == XmlPullParser.START_TAG && name.equals("city"))
                    {

                        if(parser.nextText())
                        {

                                                        System.out.println("City: "+nextText().toString);

                        }
                    }


                    eventType = parser.next();

        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.