Home » Core Java » xml » DOM » List all attributes of DOM element

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

List all attributes of DOM element

In this example we shall show you how to list all attributes of a DOM element in Java. We have implemented a method, void listAllAttributes(Element element), that lists all attributes that a specific Node contains. The steps to get a DOM object of a file and list all attributes of the DOM elements using the listAllAttributes(Element element) method is described below:

  • Obtain a new instance of a DocumentBuilderFactory, that is a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
  • Set the parser produced so as not to validate documents as they are parsed, using setValidating(boolean validating) API method of DocumentBuilderFactory, with validating set to false.
  • Create a new instance of a DocumentBuilder, using newDocumentBuilder() API method of DocumentBuilderFactory.
  • Parse the FileInputStream with the content to be parsed, using parse(InputStream is) API method of DocumentBuilder. This method parses the content of the given InputStream as an XML document and returns a new DOM Document object.
  • Get the NodeList of all the Element objects in document order with a given tag name and are contained in the document using getElementsByTagName(String tagname) API method of Document. Since the tag name is set to "entry" in the example, all elements tagged with entry will be returned.
  • Get each Node cast to Element of the NodeList, using item(int index) API method of NodeList.
  • For each one of the nodes in the nodeList, call the listAllAttributes(Element element) method of the example in order to list the attributes contained in the node. The method first gets the name of the node, using getNodeName() API method of Node. Then it takes the NamedNodeMap containing the attributes for this node, using getAttributes() API method of Node. It gets each one of the attributes, using item(int index) API method of NamedNodeMap. Each item returned is cast to Attr. For each Attr, it takes its name and its value, using getNodeName() and getNodeValue() API methods of Node,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.io.FileInputStream;

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

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

public class ListAllAttributesOfDOMElement {
	
	public static void main(String[] args) throws Exception {
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(false);
		DocumentBuilder db = dbf.newDocumentBuilder();
		
		Document doc = db.parse(new FileInputStream(new File("in.xml")));
		
		NodeList entries = doc.getElementsByTagName("entry");
		
		int num = entries.getLength();
		
		for (int i=0; i<num; i++) {
			Element node = (Element) entries.item(i);
			listAllAttributes(node);
		}
		
	}

	public static void listAllAttributes(Element element) {
		
		System.out.println("List attributes for node: " + element.getNodeName());
		
		// get a map containing the attributes of this node 
		NamedNodeMap attributes = element.getAttributes();

		// get the number of nodes in this map
		int numAttrs = attributes.getLength();

		for (int i = 0; i < numAttrs; i++) {
			Attr attr = (Attr) attributes.item(i);
			
			String attrName = attr.getNodeName();
			String attrValue = attr.getNodeValue();
			
			System.out.println("Found attribute: " + attrName + " with value: " + attrValue);
			
		}
	}

}

Input:

<?xml version="1.0" encoding="UTF-8"?>
<entries>
    <entry key="key1" attr="attr1"/>
    <entry key="key2" attr="attr2"/>
</entries>

Output:

List attributes for node: entry
Found attribute: attr with value: attr1
Found attribute: key with value: key1
List attributes for node: entry
Found attribute: attr with value: attr2
Found attribute: key with value: key2

 
This was an example of how to list all attributes of a DOM element in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of