Reputation: 16810
I have to verify Xpath expressions using Java code for which I am using the DOMParser. The problem that I am facing is that for default namespaces I need to tweak the xpath before it can be evaluated by the code. For e.g. if I want to use the following xpath -
//party[@id='party1:abc']/abc:person[@id='Trader']/trade/abc:personId[@personIdScheme='urn:xyz:person-id:PEOPLESOFT']/text()
I need to pass this to code as -
//:party[@id='party1:abc']/abc:person[@id='Trader']/:trade/abc:personId[@personIdScheme='urn:xyz:person-id:PEOPLESOFT']/text()
So basically the requirement is to put a :
before all relevant nodes where default namespace is applicable.
Can someone please help with a regex which can do this conversion efficiently?
Upvotes: 0
Views: 300
Reputation: 163342
If you need this to work on any possible XPath expression then a solution using regex is not possible, because regexes are not powerful enough to parse a recursive grammar like XPath. You will need a full XPath parser. There are several around, e.g. REx.
Upvotes: 0
Reputation: 29667
String str = "//party[@id='party1:abc']/abc:person[@id='Trader']/trade/abc:personId[@personIdScheme='urn:xyz:person-id:PEOPLESOFT']/text()";
str = str.replaceAll("/(?=\\w.*?/)(?![^\\[/]*:)","/:");
The regex looks for the /
that are not the last one, and are followed by a word character.
And it also ignores those that already have a :
before the [
or /
.
Upvotes: 0
Reputation: 3384
I know this isn't what you asked but it may serve your purpose:
String yourXPATH = "//party[@id='party1:abc']/abc:person[@id='Trader']/trade/abc:personId[@personIdScheme='urn:xyz:person-id:PEOPLESOFT']/text()";
String[] str = yourXPATH.slit("/");
String myStr = null;
while(int i=0; i<str.length; i++){
if(i==0){
myStr= str[i] +"/";
}else{
myStr = myStr + "/:" + str[i];
}
}
//then you can use myStr as the New Xpath
Upvotes: 0
Reputation: 24812
It looks like you're only adding :
after a /
if there isn't already a :
in the step, so this may work :
match /(\w+[[/])
replace with /:\1
It at least works on your example data.
Upvotes: 1