Java Reference
In-Depth Information
Each of the attributes are read from the
state
node.
System.out.println( "State Name:" +
getXMLNode(e,"state.name").getTextContent() );
System.out.println( "Code:" +
getXMLNode(e,"state.code").getTextContent() );
System.out.println( "Capital:" +
getXMLNode(e,"state.capital").getTextContent() );
System.out.println( "URL:" +
getXMLNode(e,"state.url").getTextContent() );
System.out.println( "ID:" + id);
In the above example, we made use of
getXMLNode
and
getXMLAttribute
functions. These are not built in Java functions. They are functions I created to make working
with the DOM easier. They will be discussed in the next two sections.
Implementing getXMLNode
The
getXMLNode
function is a simple function that allows you to quickly take apart
XML and get to the data you need. To understand how it works, consider the following
XML:
<firstLevel>
<secondLevel>
<thirdLevel>
</thirdLevel>
</secondLevel>
</firstLevel>
If you wanted to access the
<thirdLevel>
node, using only the DOM, you would
have to iterate through each level.
Using the
getXMLNode
function makes this much easier. To return the
<thirdLevel>
node, you would use the following code:
Node node = getXMLNode(documentRoot,"firstLevel.secondLevel.third-
Level");
The
getXMLNode
method is fairly short. It begins by creating a
StringTokenizer
object to break the name up by periods. For example, the name “firstLevel.secondLevel.third-
Level” would be broken in to three names.
StringTokenizer tok = new StringTokenizer(name,".");
Node node = e;
while( tok.hasMoreTokens() )
{
As each component of the name is parsed, we attempt to find it at the current level.
String currentName = tok.nextToken();