Element element = (Element) document.getElementsByTagName("book").item(0); NamedNodeMap attributes = element.getAttributes(); Attr titleAttribute = (Attr) attributes.getNamedItem("title"); System.out.println("Title: " + titleAttribute.getValue());
Element element = (Element) document.getElementsByTagName("person").item(0); NamedNodeMap attributes = element.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attribute = (Attr) attributes.item(i); System.out.println(attribute.getName() + ": " + attribute.getValue()); }In this example, we are getting the attributes of the first "person" element in an XML document. We then iterate over the attributes using a for loop and print out their name and value. The Node.getAttributes() method is part of the DOM (Document Object Model) API, which is included in the javax.xml package.