July 06, 2011

Android Code Sample for XML DomParsing using HashMap

You can use the sample given below for testing how to parse a xml using DomParsing and can get a clear idea to use it on your work.

 parse.xml :

<Books>
    <Book>
        <Name>Cryptography</Name>
        <Author>Harish</Author>
        <Price>$200</Price>
    </Book>
    <Book>
        <Name>Android</Name>
        <Author>Harish</Author>
        <Price>$250</Price>
    </Book>
</Books>

Method to parse xml  using dom :
public HashMap doDomParsing(String strUrl, String strParent, String[] child)
{
       HashMap hmap, hmapchild = null;
       URL url;
       hmap = new HashMap();
       
       try
       {
           //url = new URL(strUrl);
           
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();

          Document doc = db.parse(new InputSource(getClass().getResourceAsStream("/res/raw/parse.xml")));
           
           NodeList nodeList = doc.getElementsByTagName("item");
           for (int i = 0; i < nodeList.getLength(); i++)
           {
               
               Node node = nodeList.item(i);
               NodeList properties = node.getChildNodes();
               
               hmapchild = new HashMap();
               
               for(int j=0 ; j < properties.getLength() ; j++)
               {
                   Node property = properties.item(j);
                   String nodename = property.getNodeName();
                   Log.e("Node NAME", nodename);
                   
                   for(int inew =0 ;inew < child.length ; inew++)
                   {
                       if(nodename.equalsIgnoreCase(child[inew]))
                       {
                           hmapchild.put(nodename, property.getFirstChild().getNodeValue());
                       }
                   }
               }
               hmap.put(i, hmapchild);
           }
       }
       catch (Exception e)
       {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       
       return  hmap;
}

For this method we have to pass three parameters.
URL
PARENT NODE
CHILDREN

For the above xml we are parsing local file presented at raw folder. so url is empty. 

Parent is Book
child array is {Name, Author, Price}


That's it. It will parse the data store the values in Hash Map and returns that Hash Map.

No comments:

Post a Comment