You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@xalan.apache.org by sb...@locus.apache.org on 2000/03/02 20:04:50 UTC
cvs commit: xml-xalan/samples/ApplyXPath XPathAPI.java ApplyXPath.java
sboag 00/03/02 11:04:50
Modified: samples/ApplyXPath ApplyXPath.java
Added: samples/ApplyXPath XPathAPI.java
Log:
XPathAPI class
Revision Changes Path
1.2 +167 -226 xml-xalan/samples/ApplyXPath/ApplyXPath.java
Index: ApplyXPath.java
===================================================================
RCS file: /home/cvs/xml-xalan/samples/ApplyXPath/ApplyXPath.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- ApplyXPath.java 2000/02/15 15:43:45 1.1
+++ ApplyXPath.java 2000/03/02 19:04:50 1.2
@@ -74,235 +74,176 @@
* Examples:
* java ApplyXPath foo.xml /
* java ApplyXPath foo.xml /doc/name[1]/@last
+ * @see XPathAPI
*/
public class ApplyXPath
{
- protected String filename = null;
- protected String xpath = null;
+ 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>");
- }
+ /** 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
+ {
+ // Use the simple XPath API to select a node.
+ nl = XPathAPI.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);
+ }
+ }
+
+
+ /**
+ * 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
1.1 xml-xalan/samples/ApplyXPath/XPathAPI.java
Index: XPathAPI.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 "XSLT4J" 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 apache@apache.org.
*
* 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/>.
*/
import org.xml.sax.SAXException;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.apache.xalan.xpath.XPathSupport;
import org.apache.xalan.xpath.XPath;
import org.apache.xalan.xpath.XPathProcessorImpl;
import org.apache.xalan.xpath.xml.XMLParserLiaisonDefault;
import org.apache.xalan.xpath.xml.PrefixResolverDefault;
import org.apache.xalan.xpath.XObject;
/**
* The functions in this class are convenience functions into the
* low-level XPath API. We would like to eventually move these
* functions into the XPath core, but would like to do some peer
* review first and make sure we have it right.
* Please note that these only execute pure XPaths, they do not
* implement those parts of XPath extended by XSLT (for instance, the
* document() function). If you want to install XSLT functions, you
* will have to go to the low level API. Also, these functions can
* tend to be a little slow, since a bunch of objects need to be
* created for each evaluation. A faster way is to precompile the
* XPaths using the low-level API, and then just use the XPaths
* over and over.
* @see http://www.w3.org/TR/xpath
*/
public class XPathAPI
{
/**
* The simplest method to select a single node via an XPath string.
* Using this method, XPath namespace prefixes will be resolved from the context
* node, which is likely not what you want.
* @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
{
return selectSingleNode(contextNode, str, contextNode);
}
/**
* Select a single node via an XPath string. Using this method,
* XPath namespace prefixes will be resolved from the namespaceNode.
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return The first node found that matches the XPath, or null.
*/
public static Node selectSingleNode(Node contextNode, String str, Node namespaceNode)
throws SAXException
{
// Have the XObject return it's result as a NodeSet.
NodeList nl = selectNodeList(contextNode, str, namespaceNode);
// Return the first node, or null
return (nl.getLength() > 0) ? nl.item(0) : null;
}
/**
* Select a nodelist via an XPath string. Using this method,
* XPath namespace prefixes will be resolved from the namespaceNode.
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return A nodelist, should never be null.
*/
public static NodeList selectNodeList(Node contextNode, String str)
throws SAXException
{
return selectNodeList(contextNode, str, contextNode);
}
/**
* Select a nodelist via an XPath string. Using this method,
* XPath namespace prefixes will be resolved from the namespaceNode.
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return A nodelist, should never be null.
*/
public static NodeList selectNodeList(Node contextNode, String str, Node namespaceNode)
throws SAXException
{
// Execute the XPath, and have it return the result
XObject list = eval(contextNode, str, namespaceNode);
// Have the XObject return it's result as a NodeSet.
return list.nodeset();
}
/**
* Evaluate XPath string to an XObject. Using this method,
* XPath namespace prefixes will be resolved from the namespaceNode.
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
* @see org.apache.xalan.xpath.XObject
* @see org.apache.xalan.xpath.XNull
* @see org.apache.xalan.xpath.XBoolean
* @see org.apache.xalan.xpath.XNumber
* @see org.apache.xalan.xpath.XString
* @see org.apache.xalan.xpath.XRTreeFrag
*/
public static XObject eval(Node contextNode, String str)
throws SAXException
{
return eval(contextNode, str, contextNode);
}
/**
* Evaluate XPath string to an XObject. Using this method,
* XPath namespace prefixes will be resolved from the namespaceNode.
* The implementation of this is a little slow, since it creates
* a bunch of objects each time. This could be optimized to keep the
* same objects around, but then there would be thread safety issues.
* @param contextNode The node to start searching from.
* @param str A valid XPath string.
* @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
* @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
* @see org.apache.xalan.xpath.XObject
* @see org.apache.xalan.xpath.XNull
* @see org.apache.xalan.xpath.XBoolean
* @see org.apache.xalan.xpath.XNumber
* @see org.apache.xalan.xpath.XString
* @see org.apache.xalan.xpath.XRTreeFrag
*/
public static XObject eval(Node contextNode, String str, Node namespaceNode)
throws SAXException
{
// Since we don't have a XML Parser involved here, install some default support
// for things like namespaces, etc.
// (Changed from: XPathSupportDefault xpathSupport = new XPathSupportDefault();
// because XPathSupportDefault is weak in a number of areas... perhaps
// XPathSupportDefault should be done away with.)
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).
PrefixResolverDefault prefixResolver = new PrefixResolverDefault((contextNode.getNodeType() == Node.DOCUMENT_NODE)
? ((Document)contextNode).getDocumentElement() :
contextNode);
// Create the XPath object.
XPath xpath = new XPath();
// Create a XPath parser.
XPathProcessorImpl parser = new XPathProcessorImpl(xpathSupport);
parser.initXPath(xpath, str, prefixResolver);
// Execute the XPath, and have it return the result
return xpath.execute(xpathSupport, contextNode, prefixResolver);
}
}