How to Create and Evaluate XPath Expression in Java - Tutorial and Example

You can use XPathExpression from javax.xml.xpath package to create and execute XPATH expression in Java. Java API provides javax.xml.xpath package, which contains classes like Xpath, XpathFactory to work with XPATH and XML documents. By the way this is third article on Xpath, In last couple of tutorials e.g. XPATH examples to select values using attributes and my XPATH notes for Java programmer, we have seen basics of Xpath expression from XML and Java point of view. Anyone who has work with XML technologies in Java knows importance of XPATH, it is one the most useful technology to retrieve selected data from XML files. XPATH is like SQL which is used to retrieve data from relational database. Many back-office and middle-office Java application which transfers data in form of XML documents makes extensive use of XPATH expression to retrieve value for printing or for decision making. Though there are lot of open source XML libraries are available to assist with Java and XML development e.g. XML Beans. I personally prefer to use standard Java API if functionality is available there. In this Java tutorial we will learn how to create XPath expression in Java program and retrieving values from XPATH e.g. text, numbers and boolean values, which is critical for programming flow.

Java XPATH expression Example

Java Xpath expression example create and evaluate Xpath in JavaCreating XPATH expression is simple, just navigate to the node you want to retrieve by putting "/" like in our example if we want to retrieve models of each smartphone than we will write Xpath expression as /smartphones/smartphone/model. Apart from navigating to desired node in Xpath expression we have also used utility method text() to retrieve text and count() to count number of matching results. Java classes from java.xml.xpath package e.g. XPath, XPathFactory and XPathExpression is used to create and evaluate Xpath in Java programming language.


/**
* Java program to demonstrate How to create XPATH expression, How to execute XPATH
* expression to retrieve text value, numeric value and boolean value.
*
*/
package test ;

import java.io.IOException ;

import javax.xml.parsers.DocumentBuilder ;
import javax.xml.parsers.DocumentBuilderFactory ;
import javax.xml.parsers.ParserConfigurationException ;
import javax.xml.xpath.XPath ;
import javax.xml.xpath.XPathConstants ;
import javax.xml.xpath.XPathExpression ;
import javax.xml.xpath.XPathExpressionException ;
import javax.xml.xpath.XPathFactory ;

import org.w3c.dom.Document ;
import org.w3c.dom.NodeList ;
import org.xml.sax.SAXException ;


public class XPathExample {

public void xPathProcessor () throws SAXException, IOException
, XPathExpressionException, ParserConfigurationException {


//Create DocumentBuilderFactory for reading xml file
DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance () ;
DocumentBuilder builder = factory. newDocumentBuilder () ;;
Document doc = builder. parse ( "smartphone.xml" ) ;

// Create XPathFactory for creating XPath Object
XPathFactory xPathFactory = XPathFactory. newInstance () ;

// Create XPath object from XPathFactory
XPath xpath = xPathFactory. newXPath () ;

// Compile the XPath expression for getting all brands
XPathExpression xPathExpr = xpath. compile ( "/smartphones/smartphone/brand/text()" ) ;

// XPath text example : executing xpath expression in java
Object result = xPathExpr. evaluate (doc, XPathConstants. NODESET ) ;
System. out. println ( "Java Xpath text example: All brands of popular smartphones " ) ;
printXpathResult (result ) ;

//get all models by xpath expression in java
xPathExpr = xpath. compile ( "/smartphones/smartphone/model/text()" ) ;
result = xPathExpr. evaluate (doc, XPathConstants. NODESET ) ;
System. out. println ( "Java Xpath text example: All popular smartphone model " ) ;
printXpathResult (result ) ;

// XPath count example : XPath expression to count elements in xml
xPathExpr = xpath. compile ( "count(/smartphones/smartphone)" ) ;
Double count = ( Double ) xPathExpr. evaluate (doc, XPathConstants. NUMBER ) ;
System. out. println ( "XPath count example: How many Smartphones we have: " ) ;
System. out. println ( "Count of elements: " + count ) ;


// XPath conditional exampl e: Do we have any HTC smartphone
xPathExpr = xpath. compile ( "count(/smartphones/smartphone[brand='HTC']) > 0" ) ;
Boolean test = ( Boolean ) xPathExpr. evaluate (doc, XPathConstants. BOOLEAN ) ;
System. out. println ( "XPath boolean example: Do we have any HTC smartphone " ) ;
System. out. println (test ) ;

}

public void printXpathResult ( Object result ){
NodeList nodes = ( NodeList ) result ;
for ( int i = 0 ; i < nodes. getLength () ; i++ ) {
System. out. println (nodes. item (i ). getNodeValue ()) ;
}
}

public staticvoid main ( String [] args ) throws XpathExpressionException
, ParserConfigurationException, SAXException, IOException {

XPathExample xPathExample = new XPathExample () ;
xPathExample. xPathProcessor () ;
}
}

Output:
Java Xpath text example: All brands of popular smartphones
Apple
Samsung
Nokia

Java Xpath text example: All popular smartphone model
IPhone4S, IPhone4, IPhone5
Galaxy S2, Galaxy nexus, Galaxy Ace
Lumia 800, Lumia 710, Nokia N9
XPath count example: How many Smartphones we have:
Count of elements: 3.0
XPath boolean example: Do we have any HTC smartphone
False


That’s all on How to create and evaluate XPath expression in Java . We have seen How to select XML elements value as text using text() function and counted matching elements using count() function. Xpath is real interesting stuff and once you get the basics, its very easy to work with Xpath both in XML editors and Java programming language.

Other Java and XML tutorials for Java programmers



Read more: http://javarevisited.blogspot.com/2012/12/create-and-evaluate-xpath-java-example-tutorial-program.html#ixzz2ki9L8vaj
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值