List out the elements that belong to a particular XML namespace

For more information about namespaces, check out http://www.jclark.com/xml/xmlns.htm.

customers.xml (!!remove the space between ? and xml):

<? xml version="1.0" encoding="UTF-8"?>
<customers xmlns='http://www.esus.com/custns'>
   <customer id="C12345" type="prio1">
      <name>Joris Van den Bogaert</name>
      <address>
         <addressline>Handelskaai 3</addressline>
         <zip>1000</zip>
         <location>Brussels</location>
         <country>BELGIUM</country>
      </address>
   </customer>
   <destination>
      <address xmlns='http://www.esus.com/destns'>123.321.1.20</address>
   </destination>
</customers>

Main.java:

import org.w3c.dom.*;
  
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
  
import java.io.*;
   
public class Main
{
   public static void main(String []args) {
      Document doc;
  
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("customers.xml"));
 
         Element root = doc.getDocumentElement();
         root.normalize();
 
         // display all custns elements
         NodeList nl = doc.getElementsByTagNameNS("http://www.esus.com/custns", "*");
         System.out.println("Elements that belong to http://www.esus.com/custns namespace:");
         printNodeList(nl);
 
         // display all destns elements
         nl = doc.getElementsByTagNameNS("http://www.esus.com/destns", "*");
         System.out.println("Elements that belong to http://www.esus.com/destns namespace:");
         printNodeList(nl);          
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
 
   public static void printNodeList(NodeList nl) {
      for (int i=0; i<nl.getLength(); i++) {
         Node n = nl.item(i);
         System.out.println("t" + n.getNodeName());
         Node tn = n.getFirstChild();
         if (!tn.getNodeValue().trim().equals("")) {   
            System.out.println("tt" + tn.getNodeValue());
         }
         System.out.println();
      }
   }
}

outputs:

Elements that belong to http://www.esus.com/custns namespace:
	customers
 
	customer
 
	name
		Joris Van den Bogaert
 
	address
 
	addressline
		Handelskaai 3
 
	zip
		1000
 
	location
		Brussels
 
	country
		BELGIUM
 
	destination
 
Elements that belong to http://www.esus.com/destns namespace:
	address
		123.321.1.20