import java.net.URL; import oracle.xml.parser.v2.*; import org.w3c.dom.*; import org.xml.sax.*; import java.io.*; public class XPathGrep { public static void main(String[] args) throws Exception { if (args.length == 2) { XPathGrep xpg = new XPathGrep(); xpg.run(args[0],args[1]); } else { System.err.println("usage: XPathGrep filename.xml XPathExpr"); System.exit(1); } } void run(String filename, String XPath) throws Exception { URL xmlurl = URLUtils.newURL(filename); DOMParser d = new DOMParser(); try { d.parse(xmlurl); } catch(SAXParseException spe) { System.out.println("XPathGrep: File "+ filename+" is not well-formed."); System.exit(1); } catch(FileNotFoundException f) { System.out.println("XPathGrep: File "+filename+" not found."); System.exit(1); } // Cast getDocument() to an XMLDocument to have selectNodes() Method XMLDocument xmldoc = (XMLDocument)d.getDocument(); if (XPath.equals("/")) { // If the path is the root, print the entire document xmldoc.print(System.out); } else { NodeList nl = null; // Otherwise handle the matching nodes try { // Select nodes matching XPath nl = xmldoc.selectNodes(XPath); } catch (XSLException err) { System.out.println("XPathGrep: "+err.getMessage()); System.exit(1); } int found = nl.getLength(); if (found > 0) { // Loop over matches for (int z=0; z < found; z++) { XMLNode curNode = (XMLNode)nl.item(z); // Print the current node as XML Markup to the output curNode.print(System.out); // Print a new line after Text or Attribute nodes int curNodeType = curNode.getNodeType(); if (curNodeType == Node.ATTRIBUTE_NODE || curNodeType == Node.TEXT_NODE || curNodeType == Node.CDATA_SECTION_NODE) { System.out.print("\n"); } } } else { System.out.println("XPathGrep: No matches for "+ XPath); } } } } |