Checking whether an XML node has attributes

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

import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
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) {

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>
         <addressline>Handelskaai 3</addressline>