My XPath expression does not select anything in Java -
i evaluating xpath expression in java , supposed return single string
value in return.
however, 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 student is: " + name); }else{ system.out.println("error"); } }catch(xpathexpressionexception e){ system.out.println("there seems error 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 expecting see john there. can please tell me went wrong ?
this mistake many of make! xpath sensitive namespaces. xml file contains namespaced elements , these namespaces required in xpath. in xml file can use default namespace, not in xpath.
try
"/people[namespace-uri()='http://www.cmu.edu/ns/blank']/student[namespace-uri()='http://www.cmu.edu/ns/blank' , @scholarship='yes']/name[namespace-uri()='http://www.cmu.edu/ns/blank']"
and should work.
your system allows namespaces prefixes in xpath. these cannot empty. example might be:
"/a:people/a:student[@scholarship='yes']/a:name"
how map namespace prefix (a) depends on software. note prefix long mapped.
Comments
Post a Comment