[jdom-interest] XPath class

Jason Hunter jhunter at acm.org
Wed Mar 13 18:20:47 PST 2002


Laurent Bihanic wrote an XPath class that wraps an XPath engine (aka
Jaxen) and makes it real easy to get going with XPath.  I've attached it
for comments, before I check it in.  The thought is to put it in
org.jdom.xpath, and to add the jaxen and saxpath JARs to the lib
directory.  If you want to test it out, you can get these two JARs in
jdom-contrib/lib.

We pondered a bit together about if it was better to use a separate
class for this or to add the methods on Element, Attribute, Document,
etc.  It does seem to be nice to isolate all XPath topics into one
unit.  If you think about it, XSLT is external to the data structures,
and perhaps XPath should be also.  Having it separate also encourages
you to compile an XPath expression (faster to compile once) and then use
it against various contexts.  And if there's another competitor to XPath
later, that could be added externally also.

The methods are the standard Jaxen methods.  I'm wondering if we should
add a matches() method.  Thoughts on that appreciated.

And XPath gurus, please give this a test run and see how she handles.

-jh-
-------------- next part --------------
/*--

 $Id:$

 Copyright (C) 2000 Brett McLaughlin & Jason Hunter.
 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 disclaimer that follows
    these conditions in the documentation and/or other materials
    provided with the distribution.

 3. The name "JDOM" must not be used to endorse or promote products
    derived from this software without prior written permission.  For
    written permission, please contact license at jdom.org.

 4. Products derived from this software may not be called "JDOM", nor
    may "JDOM" appear in their name, without prior written permission
    from the JDOM Project Management (pm at jdom.org).

 In addition, we request (but do not require) that you include in the
 end-user documentation provided with the redistribution and/or in the
 software itself an acknowledgement equivalent to the following:
     "This product includes software developed by the
      JDOM Project (http://www.jdom.org/)."
 Alternatively, the acknowledgment may be graphical using the logos
 available at http://www.jdom.org/images/logos.

 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 JDOM AUTHORS OR THE PROJECT
 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 JDOM Project and was originally
 created by Brett McLaughlin <brett at jdom.org> and
 Jason Hunter <jhunter at jdom.org>.  For more information on the
 JDOM Project, please see <http://www.jdom.org/>.

 */

package org.jdom.xpath;


import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom.JDOMException;

import org.saxpath.SAXPathException;
import org.jaxen.JaxenException;
// import org.jaxen.jdom.XPath;


/**
 * A JDOM-oriented wrapper around XPath engines.
 *
 * @author Laurent Bihanic
 * @version $Revision: 1.114 $, $Date: 2002/03/12 06:53:57 $
 */
public final class XPath implements Serializable {

    private static final String CVS_ID =
    "@(#) $RCSfile: Element.java,v $ $Revision: 1.114 $ $Date: 2002/03/12 06:53: 57 $ $Name:  $";

   /**
    * The compiled XPath object to select nodes.  This attribute can
    * not be made final as it needs to be set upon object
    * deserialization.
    */
   private org.jaxen.jdom.XPath xPath;

   /**
    * Creates a new XPath wrapper object, compiling the specified
    * XPath expression.
    *
    * @param  expr   the XPath expression to wrap.
    *
    * @throws JDOMException   if the XPath expression is invalid.
    */
   public XPath(String expr) throws JDOMException {
      setXPath(expr);
   }

   /**
    * Compiles and sets the XPath expression wrapped by this object.
    *
    * @param  expr   the XPath expression to wrap.
    *
    * @throws JDOMException   if the XPath expression is invalid.
    */
   private void setXPath(String expr) throws JDOMException {
      try {
         xPath = new org.jaxen.jdom.XPath(expr);
      }
      catch (SAXPathException ex1) {
         throw (new JDOMException(
                        "Invalid XPath expression: \"" + expr + "\"", ex1));
      }
   }

   /**
    * Returns the wrapped XPath expression as a string.
    *
    * @return the wrapped XPath expression as a string.
    */
   public String getXPath() {
      return (xPath.toString());
   }

   /**
    * Evaluates the wrapped XPath expression and returns the list
    * of selected nodes.
    *
    * @param  context   the node to use as context for evaluating
    *                   the XPath expression.
    *
    * @return the list of selected nodes, which can be instances of
    *         the following JDOM classes: {@link Element},
    *         {@link Attribute}, {@link Text}, {@link CDATA},
    *         {@link Comment} or {@link ProcessingInstruction}.
    *
    * @throws JDOMException   if the evaluation of the XPath
    *                         expression on the specified context
    *                         failed.
    */
   public List selectNodes(Object context) throws JDOMException {
      try {
         return (xPath.selectNodes(context));
      }
      catch (JaxenException ex1) {
         throw (new JDOMException("XPath error while evaluating \"" +
                        xPath.toString() + "\": " + ex1.getMessage(), ex1));
      }
   }

   /**
    * Evaluates the wrapped XPath expression and returns the first
    * entry in the list of selected nodes.
    *
    * @param  context   the node to use as context for evaluating
    *                   the XPath expression.
    *
    * @return the first selected nodes, which is an instance of one
    *         of the following JDOM classes: {@link Element},
    *         {@link Attribute}, {@link Text}, {@link CDATA},
    *         {@link Comment} or {@link ProcessingInstruction}.
    *
    * @throws JDOMException   if the evaluation of the XPath
    *                         expression on the specified context
    *                         failed.
    */
   public Object selectSingleNode(Object context) throws JDOMException {
      try {
         return (xPath.selectSingleNode(context));
      }
      catch (JaxenException ex1) {
         throw (new JDOMException("XPath error while evaluating \"" +
                        xPath.toString() + "\": " + ex1.getMessage(), ex1));
      }
   }

   /**
    * Evaluates an XPath expression and returns the list of selected
    * nodes.
    * <p>
    * <strong>Note</strong>: This method should not be used when the
    * same XPath expression needs to be applied several times (on the
    * same or different contexts) as it requires the expression to be
    * compiled before being evaluated.  In such cases,
    * {@link #newInstance allocating} an XPath wrapper instance and
    * {@link #selectNodes(java.lang.Object) evaluating} it several
    * times is way more efficient.</p>
    *
    * @param  context   the node to use as context for evaluating
    *                   the XPath expression.
    * @param  path      the XPath expression to evaluate.
    *
    * @return the list of selected nodes, which can be instances of
    *         the following JDOM classes: {@link Element},
    *         {@link Attribute}, {@link Text}, {@link CDATA},
    *         {@link Comment} or {@link ProcessingInstruction}.
    *
    * @throws JDOMException   if the XPath expression is invalid or
    *                         its evaluation on the specified context
    *                         failed.
    */
   public static List selectNodes(Object context, String path)
                                                        throws JDOMException {
      return (new XPath(path).selectNodes(context));
   }

   /**
    * Evaluates the wrapped XPath expression and returns the first
    * entry in the list of selected nodes.
    * <p>
    * <strong>Note</strong>: This method should not be used when the
    * same XPath expression needs to be applied several times (on the
    * same or different contexts) as it requires the expression to be
    * compiled before being evaluated.  In such cases,
    * {@link #newInstance allocating} an XPath wrapper instance and
    * {@link #selectSingleNode(java.lang.Object) evaluating} it
    * several times is way more efficient.</p>
    *
    * @param  context   the element to use as context for evaluating
    *                   the XPath expression.
    * @param  path      the XPath expression to evaluate.
    *
    * @return the first selected nodes, which is an instance of one
    *         of the following JDOM classes: {@link Element},
    *         {@link Attribute}, {@link Text}, {@link CDATA},
    *         {@link Comment} or {@link ProcessingInstruction}.
    *
    * @throws JDOMException   if the XPath expression is invalid or
    *                         its evaluation on the specified context
    *                         failed.
    */
   public static Object selectSingleNode(Object context, String path)
                                                        throws JDOMException {
      return (new XPath(path).selectSingleNode(context));
   }

   /**
    * Returns the string value of the XPath expression as applied to the
    * given context.
    *
    * @param  context   the element to use as context for evaluating
    *                   the XPath expression.
    * @return the string value of the XPath expression as applied to the
    *         given context
    *
    * @throws JDOMException   if the XPath expression is invalid or
    *                         its evaluation on the specified context
    *                         failed.
    */
   public String valueOf(Object context) throws JDOMException {
      try {
         return (xPath.valueOf(context));
      }
      catch (JaxenException ex1) {
         throw (new JDOMException("XPath error while evaluating \"" +
                        xPath.toString() + "\": " + ex1.getMessage(), ex1));
      }
   }

   /**
    * Returns the number value of the XPath expression as applied to the
    * given context.
    *
    * @param  context   the element to use as context for evaluating
    *                   the XPath expression.
    * @return the number value of the XPath expression as applied to the
    *         given context
    *
    * @throws JDOMException   if the XPath expression is invalid or
    *                         its evaluation on the specified context
    *                         failed.
    */
   public Number numberValueOf(Object context) throws JDOMException {
      try {
         return (xPath.numberValueOf(context));
      }
      catch (JaxenException ex1) {
         throw (new JDOMException("XPath error while evaluating \"" +
                        xPath.toString() + "\": " + ex1.getMessage(), ex1));
      }
   }

   public String toString() {
      return (xPath.toString());
   }

   public boolean equals(Object o) {
      if (o instanceof XPath) {
         XPath x = (XPath)o;

         return ((super.equals(o)) &&
                 (xPath.toString().equals(x.xPath.toString())));
      }
      return (false);
   }

   public int hashCode() {
      return (xPath.hashCode());
   }


   /**
    * Serializes this object on the specified object stream.
    *
    * @param  out   the object stream to write the serialized
    *               object to.
    *
    * @throws IOException   if thrown by the output stream.
    */
   private void writeObject(ObjectOutputStream out) throws IOException {
      out.writeUTF(getXPath());
   }

   /**
    * Deserializes this object from the specified object stream.
    *
    * @param  in   the object stream to read the serialized
    *              object from.
    *
    * @throws IOException   if thrown by the input stream.
    */
   private void readObject(ObjectInputStream in) throws IOException {
      try {
         this.setXPath(in.readUTF());
      }
      catch (JDOMException ex1) {
         throw (new IOException(ex1.toString()));
      }
   }
}



More information about the jdom-interest mailing list