Friday, January 31, 2014

JAVA : Read Recursive XML Using Dom

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class DomFunction {
   
   
    public static void main(String args[])
    {
        try
        {
            DocumentBuilderFactory dbl=DocumentBuilderFactory.newInstance();
            DocumentBuilder db=dbl.newDocumentBuilder();
            Document doc=db.parse("http://www.freakycoders.com/android/t5_data/phonebook.xml");
           
           
           
            printAttributes(doc);
            printElement(doc);
           
           
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private static void printAttributes(Document doc)
    {
        NodeList nl=doc.getElementsByTagName("*");
        for(int i=0; i < nl.getLength(); i++)
        {
            Element e=(Element)nl.item(i);
            NamedNodeMap nnm=e.getAttributes();
           
            if(nnm != null)
            {
                for(int k=0; k < nnm.getLength(); k++)
                {
                    Node n=nnm.item(k);
                    System.out.println(e.getNodeName() + " : " + n.getNodeName() +" : " + n.getNodeValue());
                }
            }
        }
    }

    private static void printElement(Document doc) {
        NodeList nl=doc.getElementsByTagName("*");
        for(int i=0; i < nl.getLength(); i++)
        {
            Node n=nl.item(i);
            System.out.println(n.getNodeName() + " : " + n.getFirstChild().getTextContent());
           
        }
       
    }


}

No comments:

Post a Comment

Opps Part 1 : Abstraction

  Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers t...