Checking whether an XML node has attributes

Use the method hasAttributes defined in the interface Node, a superinterface of Element.

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();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("customers.xml"));
 
         Element root = doc.getDocumentElement();
         if (root.hasAttributes()) {
            System.out.println(root.getTagName() + " has attributes!");
         }
         else {
            System.out.println(root.getTagName() + " has no attributes!");
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

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

<? xml version="1.0" encoding="UTF-8"?>
<customers id="1">
   <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>
</customers>