dleslie     00/02/15 07:43:45

  Added:       samples/ApplyXPath readme.html foo.xml ApplyXPath.java
  Log:
  Replacing ValidateXPath example with ApplyXPath.
  
  Revision  Changes    Path
  1.1                  xml-xalan/samples/ApplyXPath/readme.html
  
  Index: readme.html
  ===================================================================
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  
  <html>
  <head>
        <title>Xalan Samples</title>
  </head>
  <body>
  <h2>Xalan Samples</h2>
  <p>For information about the samples (what they illustrate and how to run 
them), see <a href="../../docs/samples.html">Samples</a>.</p>
  
  
  </body>
  </html>
  
  
  
  1.1                  xml-xalan/samples/ApplyXPath/foo.xml
  
  Index: foo.xml
  ===================================================================
  <?xml version="1.0"?>
  <doc>
    <name first="David" last="Marston"/>
    <name first="David" last="Bertoni"/>
    <name first="Donald" last="Leslie"/>
    <name first="Emily" last="Farmer"/>
    <name first="Jack" last="Donohue"/>
    <name first="Myriam" last="Midy"/>
    <name first="Paul" last="Dick"/>
    <name first="Robert" last="Weir"/>
    <name first="Scott" last="Boag"/>
    <name first="Shane" last="Curcuru"/>
  </doc>
  
  
  1.1                  xml-xalan/samples/ApplyXPath/ApplyXPath.java
  
  Index: ApplyXPath.java
  ===================================================================
  /*
   * The Apache Software License, Version 1.1
   *
   *
   * Copyright (c) 1999 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Xalan" and "Apache Software Foundation" must
   *    not be used to endorse or promote products derived from this
   *    software without prior written permission. For written
   *    permission, please contact [EMAIL PROTECTED]
   *
   * 5. Products derived from this software may not be called "Apache",
   *    nor may "Apache" appear in their name, without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation and was
   * originally based on software copyright (c) 1999, Lotus
   * Development Corporation., http://www.lotus.com.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  // This file uses 4 space indents, no tabs.
  
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import org.apache.xalan.xpath.*;
  import org.apache.xalan.xpath.xml.*;
  import org.apache.xerces.dom.*;
  import org.apache.xerces.parsers.*;
  import org.w3c.dom.*;
  import org.xml.sax.*;
  
  /**
   *  Very basic utility for applying an XPath epxression to an xml file and 
printing information
   /  about the execution of the XPath object and the nodes it finds.
   *  Takes 2 arguments:
   *     (1) an xml filename
   *     (2) an XPath expression to apply to the file
   *  Examples:
   *     java ApplyXPath foo.xml /
   *     java ApplyXPath foo.xml /doc/name[1]/@last
   */
  public class ApplyXPath
  {
      protected String filename = null;
      protected String xpath = null;
  
  /** Process input args and execute the XPath.  */
      public void doMain(String[] args)
      {
          filename = args[0];
          xpath = args[1];
  
          if ((filename != null) && (filename.length() > 0)
              && (xpath != null) && (xpath.length() > 0))
          {
              InputSource in;
              try
              {
                  in = new InputSource(new FileInputStream(filename));
              }
              catch (FileNotFoundException fnf)
              {
                  System.err.println("FileInputStream of " + filename + " 
threw: " + fnf.toString());
                  fnf.printStackTrace();
                  return;
              }
  
              // Use a DOMParser from Xerces so we get a complete DOM from the 
document
              DOMParser parser = new DOMParser();
              try
              {
                  parser.parse(in);
              }
              catch(Exception e1)
              {
                  System.err.println("Parsing " + filename + " threw: " + 
e1.toString());
                  e1.printStackTrace();
                  return;
              }
  
              // Get the documentElement from the parser, which is what the 
selectNodeList method expects
              Node root = parser.getDocument().getDocumentElement();
              NodeList nl = null;
              try
              {
                  // Call the worker method that uses an independent XPath 
engine to select our nodes
                  nl = selectNodeList(root, xpath);
              }
              catch (Exception e2)
              {
                  System.err.println("selectNodeList threw: " + e2.toString() + 
" perhaps your xpath didn't select any nodes");
                  e2.printStackTrace();
                  return;
              }
              int len = nl.getLength();
              // Now that we have our list of nodes, print out debug info on 
them
              System.out.println("<nodelist len=\"" + len + "\">");
              for (int i = 0; i < len; i++)
              {
                  System.out.println(nodeToString(nl.item(i)));
              }
              System.out.println("</nodelist>");
  
          }
          else
          {
              System.out.println("Bad input args: " + filename + ", " + xpath);
          }
      }
  
  
      /**
       * Worker method to select the nodeList result of an XPath on your 
contextNode.
       * This method uses a standalone XPath which is isolated from the parser.
       * @param contextNode The node to start searching from.
       * @param str A valid XPath string.
       * @return The node list found that matches the XPath, or null.
       */
      public static NodeList selectNodeList(Node contextNode, String str)
          throws SAXException
      {
          // Since we don't have a XML Parser involved here, install some 
default support
          // for things like namespaces, etc.
          XPathSupport xpathSupport = new XMLParserLiaisonDefault();
  
          // Create an object to resolve namespace prefixes.
          // Specify that XPath namespaces will be resolved from the
          // input context node's document element if it is a root node, or else
          // the current context node (for lack of a better resolution
          // space, given the simplicity of this sample code).
          PrefixResolver prefixResolver = new 
PrefixResolverDefault((contextNode.getNodeType() == Node.DOCUMENT_NODE) ? 
((Document)contextNode).getDocumentElement() : contextNode);
  
          // Create the XPath object.
          XPath xpath = new XPath(xpathSupport, null);
  
          // Create a XPath parser.
          XPathProcessorImpl parser = new XPathProcessorImpl(xpathSupport);
          parser.initXPath(xpath, str, prefixResolver);
  
          // Unsupported debugging method: shows how it would calculate the 
xpath
          System.out.println("<diagnoseXPathString2>");
          parser.diagnoseXPathString2(str);
          System.out.println("</diagnoseXPathString2>");
  
          // Execute the XPath, and have it return the result
          XObject list = xpath.execute(xpathSupport, contextNode, 
prefixResolver);
  
          // Have the XObject return it's result as a NodeSet.
          NodeList nl = list.nodeset();
  
          // Return the whole list, or null
          return (nl.getLength() > 0) ? nl : null;
      }
  
      /**
       * Worker method to select the first node result of an XPath on your 
contextNode.
       * @param contextNode The node to start searching from.
       * @param str A valid XPath string.
       * @return The first node found that matches the XPath, or null.
       */
      public static Node selectSingleNode(Node contextNode, String str)
          throws SAXException
      {
          NodeList nl = selectNodeList(contextNode, str);
  
          // Return the first node, or null
          if (nl == null)
              return null;
          return (nl.getLength() > 0) ? nl.item(0) : null;
      }
  
  /**
   * Print information about a Node.
   * Yes, Virginia, there are better ways to do this, but this is useful for 
simple debugging.
   */
      public static String nodeToString(org.w3c.dom.Node n)
      {
          StringBuffer buf = new StringBuffer("");
          if (n == null)
          {
              buf.append("<node type=\"null\"></node>");
              return buf.toString();
          }
          buf.append("<node name=\"");
          buf.append(n.getNodeName());
          buf.append("\" type=\"");
          buf.append(nodeTypeToString(n.getNodeType()));
          buf.append("\" children=\"");
          buf.append(n.hasChildNodes());
          buf.append("\">");
          NamedNodeMap nnm = n.getAttributes();
          if (nnm != null)
          {
              buf.append(nodeAttributesToString(nnm));
          }
          buf.append(n.getNodeValue());
          buf.append("</node>");
          return buf.toString();
      }
  
  /**
   * Print information about the node attributes.
   */
      public static String nodeAttributesToString(org.w3c.dom.NamedNodeMap nnm)
      {
          StringBuffer buf = new StringBuffer("");
          if (nnm == null)
          {
              buf.append("<attrs/>");
              return buf.toString();
          }
          int len = nnm.getLength();
          buf.append("<attrs num=\"" + len + "\">");
          for (int i = 0; i < len; i++)
          {
              Node a = nnm.item(i);
              buf.append(nodeToString(a));
          }
          buf.append("</attrs>");
          return buf.toString();
      }
  
  /**  Print node type.  */
      public static String nodeTypeToString(short t)
      {
          switch (t)
          {
              case org.w3c.dom.Node.ELEMENT_NODE:
                  return "ELEMENT_NODE";
              case org.w3c.dom.Node.ATTRIBUTE_NODE:
                  return "ATTRIBUTE_NODE";
              case org.w3c.dom.Node.TEXT_NODE:
                  return "TEXT_NODE";
              case org.w3c.dom.Node.CDATA_SECTION_NODE:
                  return "CDATA_SECTION_NODE";
              case org.w3c.dom.Node.ENTITY_REFERENCE_NODE:
                  return "ENTITY_REFERENCE_NODE";
              case org.w3c.dom.Node.ENTITY_NODE:
                  return "ENTITY_NODE";
              case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
                  return "PROCESSING_INSTRUCTION_NODE";
              case org.w3c.dom.Node.COMMENT_NODE:
                  return "COMMENT_NODE";
              case org.w3c.dom.Node.DOCUMENT_NODE:
                  return "DOCUMENT_NODE";
              case org.w3c.dom.Node.DOCUMENT_TYPE_NODE:
                  return "DOCUMENT_TYPE_NODE";
              case org.w3c.dom.Node.DOCUMENT_FRAGMENT_NODE:
                  return "DOCUMENT_FRAGMENT_NODE";
              case org.w3c.dom.Node.NOTATION_NODE:
                  return "NOTATION_NODE";
              default:
                  return "#UNKNOWN";
          }
      }
  
  /** Main method to run from the command line.    */
      public static void main (String[] args)
      {
          if (args.length != 2)
          {
              System.out.println("java ApplyXPath filename.xml xpath\n"
                      + "Reads filename.xml and applies the xpath; prints the 
nodelist found.");
              return;
          }
          ApplyXPath app = new ApplyXPath();
          System.out.println("<output>");
          app.doMain(args);
          System.out.println("</output>");
      }
  } // end of class ApplyXPath
  
  
  
  

Reply via email to