FileDocCategorySizeDatePackage
ItemSearcher.javaAPI DocExample4856Thu Aug 16 16:55:14 BST 2001javaxml2

ItemSearcher

public class ItemSearcher extends Object
ItemSearcher shows how the DOM Level 2 Traversal module can be used for searching through a document.

Fields Summary
private String
docNS
The default namespace for the document to search through
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)

Provide a static entry point.

        if (args.length == 0) {
            System.out.println("No item files to search through specified.");
            return;
        }

        try {
            ItemSearcher searcher = new ItemSearcher();
            for (int i=0; i<args.length; i++) {
                System.out.println("Processing file: " + args[i]);
                searcher.search(args[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    
public voidsearch(java.lang.String filename)

This method takes a file, and searches it for specific pieces of data using DOM traversal.

param
filename name of XML file to search through.
throws
Exception - generic problem handling.


                                          
          
        // Parse into a DOM tree
        File file = new File(filename);
        DOMParser parser = new DOMParser();
        parser.parse(file.toURL().toString());
        Document doc = parser.getDocument();

        // Get node to start iterating with
        Element root = doc.getDocumentElement();
        NodeList descriptionElements = 
            root.getElementsByTagNameNS(docNS, "description");
        Element description = (Element)descriptionElements.item(0);

        // Get a NodeIterator
        NodeIterator i = ((DocumentTraversal)doc)
            .createNodeIterator(description, NodeFilter.SHOW_ALL, 
                new FormattingNodeFilter(), true);

        Node n;
        while ((n = i.nextNode()) != null) {
            System.out.println("Search phrase found: '" + n.getNodeValue() + "'");
        }