Skip to content Skip to sidebar Skip to footer

Xml Parsing Using Dom Parser

I need to parse document using DOM parser in android. I was unable to print all the node values My Sample XML is:`

Solution 1:

//Try this code..


       public String getXmlFromUrl(String url) {
                String xml = null;

                try {
                    // defaultHttpClient

                    URLConnection conn = null; 
                    InputStream inputStream = null; 
                    URL urls = new URL(url); 
                    conn = urls.openConnection(); 
                    conn.setConnectTimeout(10000); 
                    HttpURLConnection httpConn = (HttpURLConnection) conn; 
                    httpConn.setRequestMethod("GET"); 
                    httpConn.setConnectTimeout(10000); 
                    httpConn.connect(); 
                    if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
                        inputStream = httpConn.getInputStream(); 
                    } 
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); 
                    StringWriter writer=new StringWriter(); 
                    String line=""; 
                    while ( null!=(line=in.readLine())){ 
                        writer.write(line);  
                    } 
                    xml =writer.toString();  

        } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return xml;
        }




        public Document getDomElement(String xml){
                Document doc = null;
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                try {

                    DocumentBuilder db = dbf.newDocumentBuilder();
                    doc = db.parse(new InputSource(new StringReader(xml))); 
                    doc.normalize();
                    //InputSource is = new InputSource();
                   //     is.setCharacterStream(new StringReader(xml));
                       // doc = db.parse(is); 

                    } catch (ParserConfigurationException e) {
                        Log.e("Error: ", e.getMessage());
                        return null;
                    } catch (SAXException e) {
                        Log.e("Error: ", e.getMessage());
                        return null;
                    } catch (IOException e) {
                        Log.e("Error: ", e.getMessage());
                        return null;
                    }

                    return doc;
            }


     public final String getElementValue(Node elem) { 
                Node child; 
                if (elem != null) { 
                    if (elem.hasChildNodes()) { 
                        for (child = elem.getFirstChild(); child != null; child = child 
                                .getNextSibling()) { 
                            if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) { 
                                return child.getTextContent(); 
                            } 
                        } 
                    } 
                } 
                return ""; 
            } 

Solution 2:

 // All static variables
    static final String URL = "http://www.google.co.in/ig/api?news&hl=en";
    // XML node keys
    static final String KEY_ITEM = "news"; // parent node
    static final String KEY_ID = "news_entry";
    static final String KEY_NAME = "title";
    static final String KEY_COST = "url";
    static final String KEY_DESC = "snippet";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        ArrayList<HashMap<String, String>> menuItems = new    ArrayList<HashMap<String, String>>();

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

        NodeList nl = doc.getElementsByTagName(KEY_ITEM);

        for (int i = 0; i < nl.getLength(); i++) {

           HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
             NamedNodeMap attributes = e.getAttributes();
            System.out.println("attrlength"+attributes.getLength());
             for (int a = 0; a < attributes.getLength(); a++) 
             {
                     Node theAttribute = attributes.item(a);
                     System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
             }

             NodeList nl1=e.getElementsByTagName(KEY_ID);
             System.out.println("keyId"+nl1.getLength());
             for(int j=0;j<nl1.getLength();j++)
             {
                 Element e1 = (Element) nl1.item(j);

                 NodeList n = e1.getElementsByTagName(KEY_NAME);

                  for (int k = 0; k < n.getLength(); k++) {

                      Element e2 = (Element) n.item(k);
                //  System.out.println("node Title value"+e2.getNodeName());
                     NamedNodeMap attributes2 = e2.getAttributes();
                    // System.out.println("attrlength"+attributes2.getLength());
                     for (int a = 0; a < attributes2.getLength(); a++) 
                     {
                             Node theAttribute = attributes2.item(a);
                             System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());

                     }
                  }

                  NodeList n1 = e1.getElementsByTagName(KEY_COST);
                // System.out.println("title "+n.getLength());
                  for (int k = 0; k < n1.getLength(); k++) {

                      Element e2 = (Element) n1.item(k);
                //    System.out.println("node Url value");
                     NamedNodeMap attributes2 = e2.getAttributes();
                  //   System.out.println("attrlength"+attributes2.getLength());
                     for (int a = 0; a < attributes2.getLength(); a++) 
                     {
                             Node theAttribute = attributes2.item(a);
                             System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());

                     }}

                     NodeList n2 = e1.getElementsByTagName(KEY_DESC);
                    // System.out.println("title "+n.getLength());
                      for (int k = 0; k < n2.getLength(); k++) {

                          Element e2 = (Element) n2.item(k);
                    //    System.out.println("node snippet value"+e2.getNodeName());
                         NamedNodeMap attributes2 = e2.getAttributes();
                      //   System.out.println("attrlength"+attributes2.getLength());
                         for (int a = 0; a < attributes2.getLength(); a++) 
                         {
                                 Node theAttribute = attributes2.item(a);
                                 System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());

                         }
                      }  

             }



            menuItems.add(map);
        }

    }

Post a Comment for "Xml Parsing Using Dom Parser"