XPath

XPath String functions example

Photo of Chandan SinghChandan SinghMarch 3rd, 2015Last Updated: March 2nd, 2015
1 521 4 minutes read

In the previous examples, we talked about how we can query for aparticular node(s)andextract the attribute value from a node in an XML Document.

In this example, we shall see what other String operations on XPath are supported by the Java programming language.

The String operations are a range of functions that may be used to search/query. These functions operate on string variables or return a string in specific format.

 
 

Supported String functions:

Java supports the following String functions onXPath:

  • text
  • concat
  • starts-with
  • contains
  • substring-before
  • substring-after
  • substring
  • string-length
  • normalize-space
  • translate

Apart from these, there are several over-loaded versions of the methods mentioned above. We shall discuss all those methods in detail.

We will use the followingXML file for our further examples.

cricketTeam_info.xml:

<?xml version="1.0" encoding="UTF-8"?><cricketers><cricketer type="righty"><name>MS Dhoni</name><role>Captain</role><position>Wicket-Keeper</position></cricketer><cricketer type="lefty"><name>Shikhar Dhawan</name><role>              Batsman</role><position>Point</position></cricketer><cricketer type="righty"><name>Virat Kohli</name><role>Batsman</role><position>cover</position></cricketer><cricketer type="righty"><name>Shami</name><role>Bowler</role><position>SquareLeg</position></cricketer><cricketer type="lefty"><name>Zaheer Khan</name><role>Bowler</role><position>FineLeg</position></cricketer></cricketers>

Examples:

1. text()

Thetext() method is used for the string representation of the node currently selected.

XPathExpression expr = xpath.compile("//cricketer[@type='righty']/name/text()");String cricketer = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The righty cricketer is : " + cricketer);

Output:

The righty cricketer is : Shikhar Dhawan

2. concat(String arg1,String arg2,String… arg3)

Theconcat(String arg1,String arg2,String... arg3) method is used to concat strings from the evaluation of two or more XPath expressions.

XPathExpression expr = xpath.compile("concat(//cricketer[name='Shami']/@type,//cricketer[name='Zaheer Khan']/@type)");String combination = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The concat result is : " + combination);

Output:

The concat result is : rightylefty

The arguments forconcat method can also be static string objects.

XPathExpression expr = xpath.compile("concat(//cricketer[name='Shami']/@type,' Bowler'");

Output:

The concat result is : righty Bowler

3. contains(String target, String tosearch)

This method is used to search for a particular string in a target string. If the need is to find nodes with a particular String pattern, we use contains method. Look at the below code snippet how it is used.

XPathExpression expr = xpath.compile("//cricketer[contains(name,'MS')]/name/text()");String msdesc = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The Player with name containing 'MS' is : " + msdesc);

Output:

The Player with name containing 'MS' is : MS Dhoni

4. starts-with(string1, string2):

As the name indicates, thestarts-with method determines if the a particular tag in the node starts with a particular string. Look at the example below to see how it is used:

XPathExpression expr = xpath.compile("//cricketer[starts-with(name,'Za')]/name/text()");String startswith = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The Player name starting-with 'Za'  is : " + startswith);

Output:

The Player name starting-with 'Za'  is : Zaheer Khan

5. substring-before(String target, String tosearch)

Thesubstring-before is used to extract the part of string from the beginning of the string to the position where the second string in the argument starts. The example below demonstrates this clearly:

XPathExpression expr = xpath.compile("substring-before(//cricketer[name='MS Dhoni']/position,'-Keeper')");String substrbefore = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The substring before Keeper is : " + substrbefore);

Output:

The substring before Keeper is : Wicket

6. substring-after(String target, String tosearch)

Thesubstring-before is used to extract the part of string from the first occurrence of the second string argument to the end of the string. The example below demonstrates this clearly:

XPathExpression expr = xpath.compile("substring-after(//cricketer[name='MS Dhoni']/position,'Wicket-')");String substrafter = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The substring after Keeper is : " + substrafter);

Output:

The substring before Keeper is : Keeper

7. substring(String target, int startingindex, int length)

TheXPath offers a number of overloadedsubstring functions to work. Thesubstring(String target, int startingindex, int length) method is used to extract a sub-string of specified length from the index position specified. There are other substring functions that maybe used as per the requirement. Lets look at an example of the substring :

XPathExpression expr = xpath.compile("substring(//cricketer[name='MS Dhoni']/position,'1','4')");String substr = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The substring is : " + substr);

Output:

The substring is : Wick

8. string-length(string)

This method is used to calculate the size of the string. Another overloaded version is thestring-length(). This method is used to get the size of the currently selected node.

XPathExpression expr = xpath.compile("string-length(//cricketer[name='MS Dhoni']/position)");String strlength = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The length of the string is : " + strlength);

Output:

The length of the string is : 13

9. normalize-space(string)

This method is used to remove the leading and trailing spaces of the string. Another overloaded version is thenormalize-space(). This one is used to remove the leading and trailing spaces of the currently selected node.

XPathExpression expr = xpath.compile("normalize-space(//cricketer[name='Shikhar Dhawan']/role/text())");String result = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The normalized string is : " + result);

Output:

The normalized string is : Batsman

10. translate(String targetString, String stringtoreplace, String replacementstring)

Thetranslate method is used to replace the occurrences of a particular string with another string. An example will show how:

XPathExpressionexpr = xpath.compile("translate('Shikhar Dhawan','S','K')");String replacedstring = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The translated string is : " + replacedstring);

Output:

The translated string is : Khikhar Dhawan

XPathStringFunctionsDemo.java:

import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathExpression;import javax.xml.xpath.XPathFactory;import org.w3c.dom.Document;public class XpathDemo{public static void main(String[] args) throws Exception{DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();documentBuilderFactory.setNamespaceAware(true);DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();Document doc = documentBuilder.parse("src/cricketTeam_info.xml");XPathFactory xpathFactory = XPathFactory.newInstance();XPath xpath = xpathFactory.newXPath();// XPath concat exampleXPathExpression expr = xpath.compile("concat(//cricketer[name='Shami']/@type,//cricketer[name='Zaheer Khan']/@type)");String combination = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The concat result is : " + combination);// XPath starts-with exampleexpr = xpath.compile("//cricketer[starts-with(name,'Za')]/name/text()");String startswith = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The Player name starting-with 'Za'  is : " + startswith);// XPath contains exampleexpr = xpath.compile("//cricketer[contains(name,'MS')]/name/text()");String msdesc = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The Player with name containing 'MS' is : " + msdesc);// XPath substring-before exampleexpr = xpath.compile("substring-before(//cricketer[name='MS Dhoni']/position,'-Keeper')");String substrbefore = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The substring before Keeper is : " + substrbefore);   // XPath substring-after exampleexpr = xpath.compile("substring-after(//cricketer[name='MS Dhoni']/position,'Wicket-')");String substrafter = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The substring after Keeper is : " + substrafter);// XPath substring exampleexpr = xpath.compile("substring(//cricketer[name='MS Dhoni']/position,'1','4')");String substr = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The substring is : " + substr);// XPath string-length(string) exampleexpr = xpath.compile("string-length(//cricketer[name='MS Dhoni']/position)");String strlength = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The length of the string is : " + strlength);// XPath normalize-space(string) exampleexpr = xpath.compile("normalize-space(//cricketer[name='Shikhar Dhawan']/role/text())");String result = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The normalized string is : " + result);expr = xpath.compile("translate('Shikhar Dhawan','S','K')");String replacedstring = (String) expr.evaluate(doc, XPathConstants.STRING);System.out.println("The translated string is : " + replacedstring);}}

Conclusion

Here we looked at the XPath String functions supported by Java.

Download
You can download the source code of this example here:XPathStringFunctionsDemo.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Chandan SinghChandan SinghMarch 3rd, 2015Last Updated: March 2nd, 2015
1 521 4 minutes read
Photo of Chandan Singh

Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.