Regex to modify xpath expression

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?

Answer

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 /.

Leave a Reply

Your email address will not be published. Required fields are marked *