How to get all XML Elements?

Posted: March 24, 2010 in XML
Tags: , ,

public class getAllDomElements {
static public void main(String[] arg) {
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(;
File file = new File(“D:\\MyXMLFile.xml”);
if (file.exists()) {
DocumentBuilderFactory factory = DocumentBuilderFactory
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
// Get a list of all elements in the document
NodeList list = doc.getElementsByTagName(“*”);
System.out.println(“XML Elements: “);
for (int i = 0; i < list.getLength(); i++) {
// Get element
Element element = (Element) list.item(i);
} else {
System.out.print(“File not found!”);
} catch (Exception e) {

  1. himanshugpt says:

    There is something in Java which can evaluate XPath. This API is included from Java 7 which is a lot easier. If you directly want to access some node there is no need fo traversing through the nodes.

    But your code is helpful if there is a need of converting an XML Doc to a java class or something more Object Oriented.

    Himanshu Gupta

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s