I was evaluating an XPath expression in Java and it was supposed to return just a single String
value in return.
However, all I get is a blank value.
SSCCE
import javax.xml.xpath.*;
import java.io.*;
import org.xml.sax.*;
public class XPathBasic{
public static void main(String[] args){
XPathFactory factory;
XPath xPath;
XPathExpression xPathExpressionCompiled;
String xPathExpressionString;
File xmlFile;
InputSource inputSource;
try{
factory = XPathFactory.newInstance();
xPath = factory.newXPath();
xPathExpressionString = "/people/student[@scholarship='yes']/name";
xPathExpressionCompiled = xPath.compile(xPathExpressionString);
xmlFile = new File("helloWorld.xml");
inputSource = new InputSource(new FileInputStream(xmlFile));
String name = xPathExpressionCompiled.evaluate(inputSource);
if(name != null){
System.out.println("Name of the student is: " + name);
}else{
System.out.println("Error");
}
}catch(XPathExpressionException e){
System.out.println("There seems to be an error with your expression: " + e.getMessage());
}catch(IOException e){
}catch(Exception e){
}
}
}
XML
<?xml version="1.0" encoding="UTF-8" ?>
<people xmlns="http://www.cmu.edu/ns/blank"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.cmu.edu/ns/blank student.xsd">
<student scholarship="yes">
<name>John</name>
<course>Computer Technology</course>
<semester>6</semester>
<scheme>E</scheme>
</student>
<student scholarship="no">
<name>Foo</name>
<course>Industrial Electronics</course>
<semester>6</semester>
<scheme>E</scheme>
</student>
</people>
Output
Name of student is:
I was expecting to see John there. Can someone please tell me what went wrong ?