Wednesday, 23 November 2011

Simple Steps Of DOM parsing

lets take a simple xml file ,, suppose we are getting any xml from server side (mean through url)... in the bellow given format
<type category="chocolate">Truffels...</type >
<type category="icecream">crunchy choco</type >

A simple xml file. 

Lets Start:

We are going to parse it through DOM.

private void domHandler()
URL url = new URL("Your file path on server");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            NodeList nodeList = doc.getElementsByTagName("item");
            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);

                Element fstElmnt = (Element) node;
                NodeList nameList = fstElmnt.getElementsByTagName("name");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();
               String nameValue =  ((Node) nameList.item(0)).getNodeValue();

                NodeList typeList = fstElmnt.getElementsByTagName("type
                Element typeElement = (Element)
typeList .item(0);
typeList = typeElement .getChildNodes();
                String typeValue =  ((Node)
typeList .item(0)).getNodeValue());

                String typeCategory =
typeElement .getAttribute("category"));


        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);


You can also keep xml file in your assets folder and parse it: Use if else/ switch condition in parsing steps otherwise it will take much time ;)
final InputSource inputSource = new InputSource();

No comments:

Post a Comment