通过DOM解析器解析XML数据。

时间:2014-05-29 18:12:38

标签: android xml-parsing

我正在努力解决一些XMl数据。

XML数据:

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

我的解析代码:

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

但不幸的是,我反复只得到第一个城市(艾哈迈达巴德)。但我希望所有城市都能展示......

任何人都可以帮忙..

谢谢..

2 个答案:

答案 0 :(得分:1)

这是使用org.w3c.dom包的另一个实现。此代码从本地文件加载,但您可以轻松修改它以使用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();
    }

顺便说一下,第二个for循环是多余的(除非city元素可以有子元素。)你只需要遍历通过getElementsByTagName检索的列表。

答案 1 :(得分:0)

尝试此代码.. xml pull解析器优于其他xml解析器

  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();

        }
    }