Java Reference
In-Depth Information
NodeList list = node.getChildNodes();
int len = list.getLength();
for(int i=0;i<len;i++)
{
Once the current name segment is found, we move it to the
node
variable and
break
out of the search loop. The function will now return if there are no more search elements, or
continue searching if there are.
Node n = list.item(i);
if( n.getNodeName().equals(currentName) )
{
node = n;
break;
}
Finally, the
node
that was found is returned.
return node;
Once you have read a node you will likely either want to get its content text, or obtain an at-
tribute from that node. To access the content text, you simply call the
getTextContent
function of the node, as follows:
System.out.println("Value is: " + node.getTextContent() );
Obtaining an attribute from a node is discussed in the next section.
Implementing getXMLAttribute
Some XML tags have attributes. The
getXMLAttribute
method can be called to
quickly retrieve the attribute from an XML tag. Consider the following XML tag:
<state id="25">
This XML tag has one property named
id
that has a value of
25
. To access this value,
the
getXMLAttribute
function is used. This function begins by obtaining a map of
all attributes. Calling
getNamedItem
looks up the attribute, then the node value is re-
turned.
NamedNodeMap map = e.getAttributes();
Attr attr = (Attr)map.getNamedItem(name);
return attr.getNodeValue();
This obtains the attribute value.