XPath (XML Path) is an XML based coding standard that is used to locate nodes within DOM documents and is handy to access random nodes in large data collections.

In DOM Level 3, API’s were introduced to evaluate expressions of XPath in DOM document. Of many ways, the two important ways of evaluating XPath expressions are:

  • XPathEvaluator and
  • XPathResult.

The XPathEvaluator evaluates XPath expressions within specific context. It uses three methods: createExpression()createNSResolver(), and evaluate().

createExpression(expression, nsresolver)

The createExpression() method computes the XPath expression and it’s namespace information into a compiled version of a query. With this method, the XPath expression can be used multiple times, across documents, and without compiling it each time. It has significant impact when an XPath expression is used multiple times.

Syntax for createExpression() method

XPathEvaluator eval = (XPathEvaluator) response;

XPathExpression expression = eval.createExpression("/SOAP:Envelope/SOAP:Body/f:Maximum_Numbers/f:max", namespaces); 

createNSResolver(node)

The createNSResolver() method creates a new XPathNSResolver object with the namespace binding of the passed node.

Syntax for createNSResolver() method

XPathNSResolver namespaces = evaluator.createNSResolver(node);

evaluate(expression, context, nsresolver, type, result)

The evaluate() method is used to evaluate the XPath expression string and returns result of specified type.

  • The expression to be evaluated is passed as an argument.
  • The context argument is the context node which can be any of these values: Document, Element, Attribute, Text, CDATASection, Comment, ProcessingInstruction or XPathNamespace nodes. The ‘nsresolver’ argument gives the namespace information.
  • The type argument determines the type in which result has to be returned.
  • The result argument is the XPathResult Object which specifies the result object which may be reused and returned by this method. The result argument is rarely used as it is same as the return value of the method.

The type argument can be any of these values:

  • XPathResult.ANY_TYPE = 0; 
  • XPathResult.NUMBER_TYPE = 1;
  • XPathResult.STRING_TYPE = 2; 
  • XPathResult.BOOLEAN_TYPE = 3;
  • XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4;
  • XPathResult.UNORDERED_NODE_ITERATOR_TYPE  = 5;
  • XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6;
  • XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7;
  • XPathResult.ANY_UNORDERED_NODE_TYPE = 8;
  • XPathResult.FIRST_ORDERED_NODE_TYPE = 9;

Syntax for XPathEvaluator evaluator and XPathResult result

XPathEvaluator evaluator = (XPathEvaluator) response;

XPathResult result = evaluator.evaluate("book/Learning Javascript", xmldom.documentElement, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

 

›› go to examples ››