Method
Description
int
getLength()
Gets the number of nodes in this list
Node item(int
index)
‑Gets the item at the specified index value in the
collection
In Table 11.5, you'll see that the NodeList interface supports a
getLength method that returns the number of nodes in the list. This
means that we can find how many <CUSTOMER> elements there are
in the document like this:
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
public class FirstParser
{
public static void main(String[] args)
{
try {
DOMParser parser = new DOMParser();
parser.parse(args[0]);
Document
doc = parser.getDocument();
NodeList nodelist = doc.getElementsByTagName("CUSTOMER");
System.out.println(args[0] + " has " +
nodelist.getLength() + " <CUSTOMER> elements.");
} catch (Exception e)
{
e.printStackTrace(System.err);
}
}
}
You can see the results of this code here, indicating that
customer.xml has three <CUSTOMER> elements, which is
correct:
%java FirstParser customer.xml
customer.xml has 3 <CUSTOMER> elements.
If you prefer to use the -classpath switch instead of explicitly
setting the class path, you could use javac like this, assuming the
needed .jar files are in the current directory:
javac -classpath xerces.jar;xercesSamples.jar FirstParser.java
And then execute the code like this:
javac -classpath xerces.jar;xercesSamples.jar FirstParser
customer.xml
That's all it takes to get started with the XML for Java
parsers.