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(
System.in));
File file = new File(“D:\\MyXMLFile.xml”);
if (file.exists()) {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
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);
System.out.println(element.getNodeName());
}
} else {
System.out.print(“File not found!”);
}
} catch (Exception e) {
System.exit(1);
}
}

Advertisements
Comments
  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
    http://himanshugpt.wordpress.com/

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s