Search This Blog

Wednesday, June 20, 2012

DOM parsing using xml

Put the following code in the xml file.

<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 this as the xml file and read in the method.

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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.