Thursday, April 10, 2008

Read XML File Using Java

Hi all ,
this is a simple program that uses java classes to read xml files.
If an html file is written without errors then that can also be parsed using this.


import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

try {
File f = new File("filename");
// first obtain a parser that produces the DOM object tree from XML document
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

// to obtain DOM document instances from XML document
DocumentBuilder db = dbf.newDocumentBuilder();

// Document represents xml or html documents
Document doc = db.parse(f);
doc.getDocumentElement().normalize();

// first get the root
NodeList root = doc.getChildNodes();

// children of root
NodeList nodes = root.item(0).getChildNodes();
for (int i = 0; i <>

// in case there are childs of nodes[i]
NodeList temp = nodes.item(i).getChildNodes();
System.out.println(nodes.item(i).getNodeName());
System.out.println(temp.getLength());

}
} catch (Exception e) {
e.printStackTrace();
}


Suggestion : to know more about this and for those who dont want to mug up the things use netbeans
thanks..

No comments:

Post a Comment

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