The previous example displayed the entire document, but you can be
more selective than that through a process called filtering. When you
filter a document, you extract only those elements that you're
interested in.
Here's an example named searcher.java. In this case, I'll let the
user specify what document to search and what element name to search
for like this, which will display all <ITEM> elements in
customer.xml:
%java searcher customer.xml ITEM
I'll start this program by creating a new class, FindElements, to
make the programming a little easier. All I have to do is to pass the
document to search and the element name to search for to the
constructor of this new class:
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
public class searcher
{
public static void main(String args[])
{
FindElements
findElements = new FindElements(args[0], args[1]);
}
}
In the FindElements class constructor, I'll save the name of the
element to search for in a string named searchFor and then call the
displayDocument method as in the previous example to display the
document. That method will fill the displayStrings array with the
output strings, which we print:
class FindElements
{
static String displayStrings[] = new
String[1000];
static int numberDisplayLines = 0;
static String searchFor;
public FindElements (String uri, String
searchString)
{
searchFor =
searchString;
displayDocument(uri);
for(int loopIndex = 0;
loopIndex < numberDisplayLines; loopIndex++){
System.out.println(displayStrings[loopIndex]);
}
}s
In the displayDocument method, we want to display only the
elements with the name that's in the searchFor string. To find those
elements, I use the getElementsByTagName method, which returns a node
list of matching elements. I loop over all elements in that list,
calling the display method to display each element and its
children:
public static void displayDocument(String uri)
{
try {
DOMParser parser = new
DOMParser();
parser.parse(uri);
Document document =
parser.getDocument();
NodeList nodeList =
document.getElementsByTagName(searchFor);
if (nodeList != null)
{
for (int loopIndex = 0; loopIndex < nodeList.getLength();
loopIndex++ ) {
display(nodeList.item(loopIndex), "");
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
The display method is the same as in the previous example.
That's all it takes; here I search customer.xml for all
<ITEM> elements:
%java searcher customer.xml ITEM | more
You can see the results in Figure 11.2. The complete code for
searcher.java is in Listing 11.2.