Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid XPath expression exception due to presence of apostrophe in name

Tags:

java

xml

xpath

I am getting Invalid Xpath Exception for following code.

current.Name = current.Name.replace("'", "\'");
System.out.println(current.Name );
String xp1 = "//page[@name='"+current.Name+"']" ;
Element n = (Element) oDocument.selectSingleNode(xp1+"/Body/contents");

Exception occurs when the string in current.name has an apostrophe in it

current.name: "Répartition par secteur d'activité"

Error Message

like image 497
amey pawar Avatar asked Oct 20 '22 21:10

amey pawar


1 Answers

You can escape the quote by doubling it:

current.Name = current.Name.replace("'", "''");

EDIT:

For Xpath 1.0, you could try the following:

String xp1 = "//page[@name=\""+current.Name+"\"]" ;

I.e. Use double quotes instead of single quotes to delimit the name (though that means you won't be able to search for strings with a double quote.

Note also, for the second solution you won't need to replace the quotes.

like image 118
beny23 Avatar answered Oct 24 '22 10:10

beny23