| |
Attributes are special children of elements. They attach a set of
<key, value> pairs to each element.
Adding attributes uses the setAttribute() method.
Resulting XML
<top a="1" b="2"/>
|
Adding Attributes with the DOM
// Create a new document
Document doc = builder.newDocument();
// Create the top element
Element top = doc.createElement("top");
// Add an attribute
top.setAttribute("a", "1");
top.setAttribute("b", "2");
|
Retrieving attributes uses the getAttribute() method of the
Element. Since the getAttribute() method is specific to
the Element and not to Node, you'll need to cast it properly.
If an attribute is missing, the value of getAttribute() is the
empty string, "", not null. So you can safely use
equals() to compare attribute values without checking for null.
Retrieving Attributes
Node ptr;
for (ptr = top.getFirstChild();
ptr != null && ! ptr.getNodeName().equals("b");
ptr = ptr.getNextSibling()) {
}
Element elt = (Element) ptr;
if (elt == null)
System.out.println("No element b");
else if (elt.getAttribute("id").equals("")) {
System.out.println("b has no 'id' attribute");
else
System.out.println("b id=" + elt.getAttribute("id"));
|
Copyright © 1998-2002 Caucho Technology, Inc. All rights reserved.
Resin® is a registered trademark,
and HardCoretm and Quercustm are trademarks of Caucho Technology, Inc. | |
|