org.apache.xml.utils.PrefixResolver Java Examples

The following examples show how to use org.apache.xml.utils.PrefixResolver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XPathHelper.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates an XPath expression to an XObject.
 * @param contextNode the node to start searching from
 * @param str a valid XPath string
 * @param a prefix resolver to use for resolving namespace prefixes, or null
 * @return an XObject, which can be used to obtain a string, number, nodelist, etc (should never be {@code null})
 * @throws TransformerException if a syntax or other error occurs
 */
private static XObject evaluateXPath(final DomNode contextNode,
        final String str, final PrefixResolver prefixResolver) throws TransformerException {
    final XPathContext xpathSupport = new XPathContext();
    final Node xpathExpressionContext;
    if (contextNode.getNodeType() == Node.DOCUMENT_NODE) {
        xpathExpressionContext = ((Document) contextNode).getDocumentElement();
    }
    else {
        xpathExpressionContext = contextNode;
    }

    PrefixResolver resolver = prefixResolver;
    if (resolver == null) {
        resolver = new HtmlUnitPrefixResolver(xpathExpressionContext);
    }

    final boolean caseSensitive = contextNode.getPage().hasCaseSensitiveTagNames();

    final XPathAdapter xpath = new XPathAdapter(str, null, resolver, null, caseSensitive);
    final int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);
    return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
}
 
Example #2
Source File: XPathUtils.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates an XPath expression to an XObject.
 * @param contextNode the node to start searching from
 * @param str a valid XPath string
 * @param a prefix resolver to use for resolving namespace prefixes, or null
 * @return an XObject, which can be used to obtain a string, number, nodelist, etc (should never be {@code null})
 * @throws TransformerException if a syntax or other error occurs
 */
private static XObject evaluateXPath(final DomNode contextNode,
        final String str, final PrefixResolver prefixResolver) throws TransformerException {
    final XPathContext xpathSupport = new XPathContext();
    final Node xpathExpressionContext;
    if (contextNode.getNodeType() == Node.DOCUMENT_NODE) {
        xpathExpressionContext = ((Document) contextNode).getDocumentElement();
    }
    else {
        xpathExpressionContext = contextNode;
    }

    PrefixResolver resolver = prefixResolver;
    if (resolver == null) {
        resolver = new HtmlUnitPrefixResolver(xpathExpressionContext);
    }

    final boolean caseSensitive = contextNode.getPage().hasCaseSensitiveTagNames();
    final boolean attributeCaseSensitive = caseSensitive
                                                || contextNode.getPage().getWebClient()
                                                    .getBrowserVersion().hasFeature(XPATH_ATTRIBUTE_CASE_SENSITIVE);
    final XPathAdapter xpath = new XPathAdapter(str, null, resolver, null, caseSensitive, attributeCaseSensitive);
    final int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);
    return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
}
 
Example #3
Source File: CachedXPathAPI.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 *   Evaluate XPath string to an XObject.
 *   XPath namespace prefixes are resolved from the namespaceNode.
 *   The implementation of this is a little slow, since it creates
 *   a number of objects each time it is called.  This could be optimized
 *   to keep the same objects around, but then thread-safety issues would arise.
 *
 *   @param contextNode The node to start searching from.
 *   @param str A valid XPath string.
 *   @param prefixResolver Will be called if the parser encounters namespace
 *                         prefixes, to resolve the prefixes to URLs.
 *   @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
 *   @see org.apache.xpath.objects.XObject
 *   @see org.apache.xpath.objects.XNull
 *   @see org.apache.xpath.objects.XBoolean
 *   @see org.apache.xpath.objects.XNumber
 *   @see org.apache.xpath.objects.XString
 *   @see org.apache.xpath.objects.XRTreeFrag
 *
 * @throws TransformerException
 */
public  XObject eval(
        Node contextNode, String str, PrefixResolver prefixResolver)
          throws TransformerException
{

  // Since we don't have a XML Parser involved here, install some default support
  // for things like namespaces, etc.
  // (Changed from: XPathContext xpathSupport = new XPathContext();
  //    because XPathContext is weak in a number of areas... perhaps
  //    XPathContext should be done away with.)
  // Create the XPath object.
  XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);

  // Create an XPathContext that doesn't support pushing and popping of
  // variable resolution scopes.  Sufficient for simple XPath 1.0 expressions.
  XPathContext xpathSupport = new XPathContext(false);

  // Execute the XPath, and have it return the result
  int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);

  return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
}
 
Example #4
Source File: XPathAPI.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 *   Evaluate XPath string to an XObject.
 *   XPath namespace prefixes are resolved from the namespaceNode.
 *   The implementation of this is a little slow, since it creates
 *   a number of objects each time it is called.  This could be optimized
 *   to keep the same objects around, but then thread-safety issues would arise.
 *
 *   @param contextNode The node to start searching from.
 *   @param str A valid XPath string.
 *   @param prefixResolver Will be called if the parser encounters namespace
 *                         prefixes, to resolve the prefixes to URLs.
 *   @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null.
 *   @see org.apache.xpath.objects.XObject
 *   @see org.apache.xpath.objects.XNull
 *   @see org.apache.xpath.objects.XBoolean
 *   @see org.apache.xpath.objects.XNumber
 *   @see org.apache.xpath.objects.XString
 *   @see org.apache.xpath.objects.XRTreeFrag
 *
 * @throws TransformerException
 */
public static XObject eval(
        Node contextNode, String str, PrefixResolver prefixResolver)
          throws TransformerException
{

  // Since we don't have a XML Parser involved here, install some default support
  // for things like namespaces, etc.
  // (Changed from: XPathContext xpathSupport = new XPathContext();
  //    because XPathContext is weak in a number of areas... perhaps
  //    XPathContext should be done away with.)
  // Create the XPath object.
  XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);

  // Create an XPathContext that doesn't support pushing and popping of
  // variable resolution scopes.  Sufficient for simple XPath 1.0 expressions.
  XPathContext xpathSupport = new XPathContext(false);

  // Execute the XPath, and have it return the result
  int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode);

  return xpath.execute(xpathSupport, ctxtNode, prefixResolver);
}
 
Example #5
Source File: Lexer.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Create a Lexer object.
 *
 * @param compiler The owning compiler for this lexer.
 * @param resolver The prefix resolver for mapping qualified name prefixes 
 *                 to namespace URIs.
 * @param xpathProcessor The parser that is processing strings to opcodes.
 */
Lexer(Compiler compiler, PrefixResolver resolver,
      XPathParser xpathProcessor)
{

  m_compiler = compiler;
  m_namespaceContext = resolver;
  m_processor = xpathProcessor;
}
 
Example #6
Source File: XPathHelper.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates an XPath expression from the specified node, returning the resultant nodes.
 *
 * @param <T> the type class
 * @param node the node to start searching from
 * @param xpathExpr the XPath expression
 * @param resolver the prefix resolver to use for resolving namespace prefixes, or null
 * @return the list of objects found
 */
@SuppressWarnings("unchecked")
public static <T> List<T> getByXPath(final DomNode node, final String xpathExpr,
        final PrefixResolver resolver) {
    if (xpathExpr == null) {
        throw new IllegalArgumentException("Null is not a valid XPath expression");
    }

    PROCESS_XPATH_.set(Boolean.TRUE);
    final List<T> list = new ArrayList<>();
    try {
        final XObject result = evaluateXPath(node, xpathExpr, resolver);

        if (result instanceof XNodeSet) {
            final NodeList nodelist = ((XNodeSet) result).nodelist();
            for (int i = 0; i < nodelist.getLength(); i++) {
                list.add((T) nodelist.item(i));
            }
        }
        else if (result instanceof XNumber) {
            list.add((T) Double.valueOf(result.num()));
        }
        else if (result instanceof XBoolean) {
            list.add((T) Boolean.valueOf(result.bool()));
        }
        else if (result instanceof XString) {
            list.add((T) result.str());
        }
        else {
            throw new RuntimeException("Unproccessed " + result.getClass().getName());
        }
    }
    catch (final Exception e) {
        throw new RuntimeException("Could not retrieve XPath >" + xpathExpr + "< on " + node, e);
    }
    finally {
        PROCESS_XPATH_.set(Boolean.FALSE);
    }
    return list;
}
 
Example #7
Source File: XPathUtils.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates an XPath expression from the specified node, returning the resultant nodes.
 *
 * @param <T> the type class
 * @param node the node to start searching from
 * @param xpathExpr the XPath expression
 * @param resolver the prefix resolver to use for resolving namespace prefixes, or null
 * @return the list of objects found
 */
@SuppressWarnings("unchecked")
public static <T> List<T> getByXPath(final DomNode node, final String xpathExpr, final PrefixResolver resolver) {
    if (xpathExpr == null) {
        throw new NullPointerException("Null is not a valid XPath expression");
    }

    PROCESS_XPATH_.set(Boolean.TRUE);
    final List<T> list = new ArrayList<>();
    try {
        final XObject result = evaluateXPath(node, xpathExpr, resolver);

        if (result instanceof XNodeSet) {
            final NodeList nodelist = ((XNodeSet) result).nodelist();
            for (int i = 0; i < nodelist.getLength(); i++) {
                list.add((T) nodelist.item(i));
            }
        }
        else if (result instanceof XNumber) {
            list.add((T) Double.valueOf(result.num()));
        }
        else if (result instanceof XBoolean) {
            list.add((T) Boolean.valueOf(result.bool()));
        }
        else if (result instanceof XString) {
            list.add((T) result.str());
        }
        else {
            throw new RuntimeException("Unproccessed " + result.getClass().getName());
        }
    }
    catch (final Exception e) {
        throw new RuntimeException("Could not retrieve XPath >" + xpathExpr + "< on " + node, e);
    }
    finally {
        PROCESS_XPATH_.set(Boolean.FALSE);
    }
    return list;
}
 
Example #8
Source File: KeyTable.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Build a keys table.
 * @param doc The owner document key.
 * @param nscontext The stylesheet's namespace context.
 * @param name The key name
 * @param keyDeclarations The stylesheet's xsl:key declarations.
 *
 * @throws javax.xml.transform.TransformerException
 */
public KeyTable(
        int doc, PrefixResolver nscontext, QName name, Vector keyDeclarations, XPathContext xctxt)
          throws javax.xml.transform.TransformerException
{
  m_docKey = doc;
  m_keyDeclarations = keyDeclarations;
  KeyIterator ki = new KeyIterator(name, keyDeclarations);

  m_keyNodes = new XNodeSet(ki);
  m_keyNodes.allowDetachToRelease(false);
  m_keyNodes.setRoot(doc, xctxt);
}
 
Example #9
Source File: XPath.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Construct an XPath object.  
 *
 * (Needs review -sc) This method initializes an XPathParser/
 * Compiler and compiles the expression.
 * @param exprString The XPath expression.
 * @param locator The location of the expression, may be null.
 * @param prefixResolver A prefix resolver to use to resolve prefixes to 
 *                       namespace URIs.
 * @param type one of {@link #SELECT} or {@link #MATCH}.
 * @param errorListener The error listener, or null if default should be used.
 *
 * @throws javax.xml.transform.TransformerException if syntax or other error.
 */
public XPath(
        String exprString, SourceLocator locator, 
        PrefixResolver prefixResolver, int type,
        ErrorListener errorListener, FunctionTable aTable)
          throws javax.xml.transform.TransformerException
{ 
  m_funcTable = aTable;     
  if(null == errorListener)
    errorListener = new org.apache.xml.utils.DefaultErrorHandler();
  
  m_patternString = exprString;

  XPathParser parser = new XPathParser(errorListener, locator);
  Compiler compiler = new Compiler(errorListener, locator, m_funcTable);

  if (SELECT == type)
    parser.initXPath(compiler, exprString, prefixResolver);
  else if (MATCH == type)
    parser.initMatchPattern(compiler, exprString, prefixResolver);
  else
    throw new RuntimeException(XSLMessages.createXPATHMessage(
          XPATHErrorResources.ER_CANNOT_DEAL_XPATH_TYPE, 
          new Object[]{Integer.toString(type)})); 
          //"Can not deal with XPath type: " + type);

  // System.out.println("----------------");
  Expression expr = compiler.compile(0);

  // System.out.println("expr: "+expr);
  this.setExpression(expr);
  
  if((null != locator) && locator instanceof ExpressionNode)
  {
  	expr.exprSetParent((ExpressionNode)locator);
  }

}
 
Example #10
Source File: XPath.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Construct an XPath object.  
 *
 * (Needs review -sc) This method initializes an XPathParser/
 * Compiler and compiles the expression.
 * @param exprString The XPath expression.
 * @param locator The location of the expression, may be null.
 * @param prefixResolver A prefix resolver to use to resolve prefixes to 
 *                       namespace URIs.
 * @param type one of {@link #SELECT} or {@link #MATCH}.
 * @param errorListener The error listener, or null if default should be used.
 *
 * @throws javax.xml.transform.TransformerException if syntax or other error.
 */
public XPath(
        String exprString, SourceLocator locator, PrefixResolver prefixResolver, int type,
        ErrorListener errorListener)
          throws javax.xml.transform.TransformerException
{ 
  initFunctionTable();     
  if(null == errorListener)
    errorListener = new org.apache.xml.utils.DefaultErrorHandler();
  
  m_patternString = exprString;

  XPathParser parser = new XPathParser(errorListener, locator);
  Compiler compiler = new Compiler(errorListener, locator, m_funcTable);

  if (SELECT == type)
    parser.initXPath(compiler, exprString, prefixResolver);
  else if (MATCH == type)
    parser.initMatchPattern(compiler, exprString, prefixResolver);
  else
    throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CANNOT_DEAL_XPATH_TYPE, new Object[]{Integer.toString(type)})); //"Can not deal with XPath type: " + type);

  // System.out.println("----------------");
  Expression expr = compiler.compile(0);

  // System.out.println("expr: "+expr);
  this.setExpression(expr);
  
  if((null != locator) && locator instanceof ExpressionNode)
  {
  	expr.exprSetParent((ExpressionNode)locator);
  }

}
 
Example #11
Source File: LocPathIterator.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Create a LocPathIterator object.
 *
 * @param nscontext The namespace context for this iterator,
 * should be OK if null.
 */
protected LocPathIterator(PrefixResolver nscontext)
{

  setLocPathIterator(this);
  m_prefixResolver = nscontext;
}
 
Example #12
Source File: PredicatedNodeTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Process the predicates.
 *
 * @param context The current context node.
 * @param xctxt The XPath runtime context.
 *
 * @return the result of executing the predicate expressions.
 *
 * @throws javax.xml.transform.TransformerException
 */
boolean executePredicates(int context, XPathContext xctxt)
        throws javax.xml.transform.TransformerException
{
  
  int nPredicates = getPredicateCount();
  // System.out.println("nPredicates: "+nPredicates);
  if (nPredicates == 0)
    return true;

  PrefixResolver savedResolver = xctxt.getNamespaceContext();

  try
  {
    m_predicateIndex = 0;
    xctxt.pushSubContextList(this);
    xctxt.pushNamespaceContext(m_lpi.getPrefixResolver());
    xctxt.pushCurrentNode(context);

    for (int i = 0; i < nPredicates; i++)
    {
      // System.out.println("Executing predicate expression - waiting count: "+m_lpi.getWaitingCount());
      XObject pred = m_predicates[i].execute(xctxt);
      // System.out.println("\nBack from executing predicate expression - waiting count: "+m_lpi.getWaitingCount());
      // System.out.println("pred.getType(): "+pred.getType());
      if (XObject.CLASS_NUMBER == pred.getType())
      {
        if (DEBUG_PREDICATECOUNTING)
        {
          System.out.flush();
          System.out.println("\n===== start predicate count ========");
          System.out.println("m_predicateIndex: " + m_predicateIndex);
          // System.out.println("getProximityPosition(m_predicateIndex): "
          //                   + getProximityPosition(m_predicateIndex));
          System.out.println("pred.num(): " + pred.num());
        }

        int proxPos = this.getProximityPosition(m_predicateIndex);
        int predIndex = (int) pred.num();
        if (proxPos != predIndex)
        {
          if (DEBUG_PREDICATECOUNTING)
          {
            System.out.println("\nnode context: "+nodeToString(context));
            System.out.println("index predicate is false: "+proxPos);
            System.out.println("\n===== end predicate count ========");
          }
          return false;
        }
        else if (DEBUG_PREDICATECOUNTING)
        {
          System.out.println("\nnode context: "+nodeToString(context));
          System.out.println("index predicate is true: "+proxPos);
          System.out.println("\n===== end predicate count ========");
        }
        
        // If there is a proximity index that will not change during the 
        // course of itteration, then we know there can be no more true 
        // occurances of this predicate, so flag that we're done after 
        // this.
        //
        // bugzilla 14365
        // We can't set m_foundLast = true unless we're sure that -all-
        // remaining parameters are stable, or else last() fails. Fixed so
        // only sets m_foundLast if on the last predicate
        if(m_predicates[i].isStableNumber() && i == nPredicates - 1)
        {
          m_foundLast = true;
        }
      }
      else if (!pred.bool())
        return false;

      countProximityPosition(++m_predicateIndex);
    }
  }
  finally
  {
    xctxt.popCurrentNode();
    xctxt.popNamespaceContext();
    xctxt.popSubContextList();
    m_predicateIndex = -1;
  }

  return true;
}
 
Example #13
Source File: XPathParser.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Given an string, init an XPath object for pattern matches,
 * in order that a parse doesn't
 * have to be done each time the expression is evaluated.
 * @param compiler The XPath object to be initialized.
 * @param expression A String representing the XPath.
 * @param namespaceContext An object that is able to resolve prefixes in
 * the XPath to namespaces.
 *
 * @throws javax.xml.transform.TransformerException
 */
public void initMatchPattern(
        Compiler compiler, String expression, PrefixResolver namespaceContext)
          throws javax.xml.transform.TransformerException
{

  m_ops = compiler;
  m_namespaceContext = namespaceContext;
  m_functionTable = compiler.getFunctionTable();

  Lexer lexer = new Lexer(compiler, namespaceContext, this);

  lexer.tokenize(expression);

  m_ops.setOp(0, OpCodes.OP_MATCHPATTERN);
  m_ops.setOp(OpMap.MAPINDEX_LENGTH, 2);

  nextToken();
  Pattern();

  if (null != m_token)
  {
    String extraTokens = "";

    while (null != m_token)
    {
      extraTokens += "'" + m_token + "'";

      nextToken();

      if (null != m_token)
        extraTokens += ", ";
    }

    error(XPATHErrorResources.ER_EXTRA_ILLEGAL_TOKENS,
          new Object[]{ extraTokens });  //"Extra illegal tokens: "+extraTokens);
  }

  // Terminate for safety.
  m_ops.setOp(m_ops.getOp(OpMap.MAPINDEX_LENGTH), OpCodes.ENDOP);
  m_ops.setOp(OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH)+1);

  m_ops.shrink();
}
 
Example #14
Source File: XPathParser.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
  * Given an string, init an XPath object for selections,
  * in order that a parse doesn't
  * have to be done each time the expression is evaluated.
  * 
  * @param compiler The compiler object.
  * @param expression A string conforming to the XPath grammar.
  * @param namespaceContext An object that is able to resolve prefixes in
  * the XPath to namespaces.
  *
  * @throws javax.xml.transform.TransformerException
  */
 public void initXPath(
         Compiler compiler, String expression, PrefixResolver namespaceContext)
           throws javax.xml.transform.TransformerException
 {

   m_ops = compiler;
   m_namespaceContext = namespaceContext;
   m_functionTable = compiler.getFunctionTable();

   Lexer lexer = new Lexer(compiler, namespaceContext, this);

   lexer.tokenize(expression);

   m_ops.setOp(0,OpCodes.OP_XPATH);
   m_ops.setOp(OpMap.MAPINDEX_LENGTH,2);
   
   
// Patch for Christine's gripe. She wants her errorHandler to return from
// a fatal error and continue trying to parse, rather than throwing an exception.
// Without the patch, that put us into an endless loop.
//
// %REVIEW% Is there a better way of doing this?
// %REVIEW% Are there any other cases which need the safety net?
// 	(and if so do we care right now, or should we rewrite the XPath
//	grammar engine and can fix it at that time?)
try {

     nextToken();
     Expr();

     if (null != m_token)
     {
       String extraTokens = "";

       while (null != m_token)
       {
         extraTokens += "'" + m_token + "'";

         nextToken();

         if (null != m_token)
           extraTokens += ", ";
       }

       error(XPATHErrorResources.ER_EXTRA_ILLEGAL_TOKENS,
             new Object[]{ extraTokens });  //"Extra illegal tokens: "+extraTokens);
     }

   } 
   catch (org.apache.xpath.XPathProcessorException e)
   {
  if(CONTINUE_AFTER_FATAL_ERROR.equals(e.getMessage()))
  {
	// What I _want_ to do is null out this XPath.
	// I doubt this has the desired effect, but I'm not sure what else to do.
	// %REVIEW%!!!
	initXPath(compiler, "/..",  namespaceContext);
  }
  else
	throw e;
   }

   compiler.shrink();
 }
 
Example #15
Source File: FilterExprIteratorSimple.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Execute the expression.  Meant for reuse by other FilterExpr iterators 
 * that are not derived from this object.
 */
public static XNodeSet executeFilterExpr(int context, XPathContext xctxt, 
												PrefixResolver prefixResolver,
												boolean isTopLevel,
												int stackFrame,
												Expression expr )
  throws org.apache.xml.utils.WrappedRuntimeException
{
  PrefixResolver savedResolver = xctxt.getNamespaceContext();
  XNodeSet result = null;

  try
  {
    xctxt.pushCurrentNode(context);
    xctxt.setNamespaceContext(prefixResolver);

    // The setRoot operation can take place with a reset operation, 
    // and so we may not be in the context of LocPathIterator#nextNode, 
    // so we have to set up the variable context, execute the expression, 
    // and then restore the variable context.

    if (isTopLevel)
    {
      // System.out.println("calling m_expr.execute(getXPathContext())");
      VariableStack vars = xctxt.getVarStack();

      // These three statements need to be combined into one operation.
      int savedStart = vars.getStackFrame();
      vars.setStackFrame(stackFrame);

      result = (org.apache.xpath.objects.XNodeSet) expr.execute(xctxt);
      result.setShouldCacheNodes(true);

      // These two statements need to be combined into one operation.
      vars.setStackFrame(savedStart);
    }
    else
        result = (org.apache.xpath.objects.XNodeSet) expr.execute(xctxt);

  }
  catch (javax.xml.transform.TransformerException se)
  {

    // TODO: Fix...
    throw new org.apache.xml.utils.WrappedRuntimeException(se);
  }
  finally
  {
    xctxt.popCurrentNode();
    xctxt.setNamespaceContext(savedResolver);
  }
  return result;
}
 
Example #16
Source File: DomNode.java    From htmlunit with Apache License 2.0 3 votes vote down vote up
/**
 * Evaluates the specified XPath expression from this node, returning the first matching element,
 * or {@code null} if no node matches the specified XPath expression.
 *
 * @param xpathExpr the XPath expression
 * @param <X> the expression type
 * @param resolver the prefix resolver to use for resolving namespace prefixes, or null
 * @return the first element matching the specified XPath expression
 * @see #getByXPath(String)
 * @see #getCanonicalXPath()
 */
@SuppressWarnings("unchecked")
public <X> X getFirstByXPath(final String xpathExpr, final PrefixResolver resolver) {
    final List<?> results = getByXPath(xpathExpr, resolver);
    if (results.isEmpty()) {
        return null;
    }
    return (X) results.get(0);
}
 
Example #17
Source File: XPathContext.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Push the current context node, expression node, and prefix resolver.
 *
 * @param cn the <a href="http://www.w3.org/TR/xslt#dt-current-node">current node</a>.
 * @param en the sub-expression context node.
 * @param nc the namespace context (prefix resolver.
 */
public final void pushExpressionState(int cn, int en, PrefixResolver nc)
{
  m_currentNodes.push(cn);
  m_currentExpressionNodes.push(cn);
  m_prefixResolvers.push(nc);
}
 
Example #18
Source File: DomNode.java    From HtmlUnit-Android with Apache License 2.0 3 votes vote down vote up
/**
 * Evaluates the specified XPath expression from this node, returning the first matching element,
 * or {@code null} if no node matches the specified XPath expression.
 *
 * @param xpathExpr the XPath expression
 * @param <X> the expression type
 * @param resolver the prefix resolver to use for resolving namespace prefixes, or null
 * @return the first element matching the specified XPath expression
 * @see #getByXPath(String)
 * @see #getCanonicalXPath()
 */
@SuppressWarnings("unchecked")
public <X> X getFirstByXPath(final String xpathExpr, final PrefixResolver resolver) {
    final List<?> results = getByXPath(xpathExpr, resolver);
    if (results.isEmpty()) {
        return null;
    }
    return (X) results.get(0);
}
 
Example #19
Source File: DTMManagerDefault.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * NEEDSDOC Method createDTMIterator
 *
 *
 * NEEDSDOC @param xpathString
 * NEEDSDOC @param presolver
 *
 * NEEDSDOC (createDTMIterator) @return
 */
synchronized public DTMIterator createDTMIterator(String xpathString,
                                     PrefixResolver presolver)
{

  /** @todo: implement this org.apache.xml.dtm.DTMManager abstract method */
  return null;
}
 
Example #20
Source File: XPath.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Given an expression and a context, evaluate the XPath
 * and return the result.
 * 
 * @param xctxt The execution context.
 * @param contextNode The node that "." expresses.
 * @param namespaceContext The context in which namespaces in the
 * XPath are supposed to be expanded.
 *
 * @return The result of the XPath or null if callbacks are used.
 * @throws TransformerException thrown if
 * the error condition is severe enough to halt processing.
 *
 * @throws javax.xml.transform.TransformerException
 * @xsl.usage experimental
 */
public XObject execute(
        XPathContext xctxt, org.w3c.dom.Node contextNode, 
        PrefixResolver namespaceContext)
          throws javax.xml.transform.TransformerException
{
  return execute(
        xctxt, xctxt.getDTMHandleFromNode(contextNode), 
        namespaceContext);
}
 
Example #21
Source File: XPath.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Construct an XPath object.  
 *
 * (Needs review -sc) This method initializes an XPathParser/
 * Compiler and compiles the expression.
 * @param exprString The XPath expression.
 * @param locator The location of the expression, may be null.
 * @param prefixResolver A prefix resolver to use to resolve prefixes to 
 *                       namespace URIs.
 * @param type one of {@link #SELECT} or {@link #MATCH}.
 *
 * @throws javax.xml.transform.TransformerException if syntax or other error.
 */
public XPath(
        String exprString, SourceLocator locator, PrefixResolver prefixResolver, int type)
          throws javax.xml.transform.TransformerException
{  
  this(exprString, locator, prefixResolver, type, null);    
}
 
Example #22
Source File: BasicTestIterator.java    From j2objc with Apache License 2.0 2 votes vote down vote up
/**
 * Create a LocPathIterator object.
 *
 * @param nscontext The namespace context for this iterator,
 * should be OK if null.
 */
protected BasicTestIterator(PrefixResolver nscontext)
{

  super(nscontext);
}
 
Example #23
Source File: Compiler.java    From j2objc with Apache License 2.0 2 votes vote down vote up
/**
 * Set the current namespace context for the xpath.
 *
 * @param pr The resolver for prefixes in the XPath expression.
 */
public void setNamespaceContext(PrefixResolver pr)
{
  m_currentPrefixResolver = pr;
}
 
Example #24
Source File: Compiler.java    From j2objc with Apache License 2.0 2 votes vote down vote up
/**
 * Get the current namespace context for the xpath.
 *
 * @return The current prefix resolver, *may* be null, though hopefully not.
 */
public PrefixResolver getNamespaceContext()
{
  return m_currentPrefixResolver;
}
 
Example #25
Source File: DomNode.java    From HtmlUnit-Android with Apache License 2.0 2 votes vote down vote up
/**
 * Evaluates the specified XPath expression from this node, returning the matching elements.
 *
 * @param xpathExpr the XPath expression to evaluate
 * @param resolver the prefix resolver to use for resolving namespace prefixes, or null
 * @return the elements which match the specified XPath expression
 * @see #getFirstByXPath(String)
 * @see #getCanonicalXPath()
 */
public List<?> getByXPath(final String xpathExpr, final PrefixResolver resolver) {
    return XPathUtils.getByXPath(this, xpathExpr, resolver);
}
 
Example #26
Source File: DTMManager.java    From j2objc with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new <code>DTMIterator</code> based on an XPath
 * <a href="http://www.w3.org/TR/xpath#NT-LocationPath>LocationPath</a> or
 * a <a href="http://www.w3.org/TR/xpath#NT-UnionExpr">UnionExpr</a>.
 *
 * @param xpathString Must be a valid string expressing a
 * <a href="http://www.w3.org/TR/xpath#NT-LocationPath>LocationPath</a> or
 * a <a href="http://www.w3.org/TR/xpath#NT-UnionExpr">UnionExpr</a>.
 *
 * @param presolver An object that can resolve prefixes to namespace URLs.
 *
 * @return The newly created <code>DTMIterator</code>.
 */
public abstract DTMIterator createDTMIterator(String xpathString,
        PrefixResolver presolver);
 
Example #27
Source File: WalkingIteratorSorted.java    From j2objc with Apache License 2.0 2 votes vote down vote up
/**
 * Create a WalkingIteratorSorted object.
 *
 * @param nscontext The namespace context for this iterator,
 * should be OK if null.
 */
public WalkingIteratorSorted(PrefixResolver nscontext)
{
  super(nscontext);
}
 
Example #28
Source File: XPathContext.java    From j2objc with Apache License 2.0 2 votes vote down vote up
/**
 * Push a current namespace context for the xpath.
 *
 * @param pr the prefix resolver to be used for resolving prefixes to 
 *         namespace URLs.
 */
public final void pushNamespaceContext(PrefixResolver pr)
{
  m_prefixResolvers.push(pr);
}
 
Example #29
Source File: XPathContext.java    From j2objc with Apache License 2.0 2 votes vote down vote up
/**
 * Get the current namespace context for the xpath.
 *
 * @param pr the prefix resolver to be used for resolving prefixes to 
 *         namespace URLs.
 */
public final void setNamespaceContext(PrefixResolver pr)
{
  m_prefixResolvers.setTop(pr);
}
 
Example #30
Source File: XPathContext.java    From j2objc with Apache License 2.0 2 votes vote down vote up
/**
 * Get the current namespace context for the xpath.
 *
 * @return the current prefix resolver for resolving prefixes to 
 *         namespace URLs.
 */
public final PrefixResolver getNamespaceContext()
{
  return (PrefixResolver) m_prefixResolvers.peek();
}