Gabriel S.
Gabriel S.

Reputation: 1347

Altering element names in an XPath expression

I'm looking for a way to programatically change any given XPath 1.0 expression in such a way that element names in the expression that are not already prefixed must become prefixed with a predefined string.

Here are some examples (consider bk as the predefined prefix):

book must become bk:book

/bookstore/book/title must become /bk:bookstore/bk:book/bk:title

//book/title/text() must become //bk:book/bk:title/text()

/x:bookstore/book/ must become /x:bookstore/bk:book/

/bookstore/book[price>35.00] must become /bk:bookstore/bk:book[bk:price>35.00]

child::para[attribute::type='warning'][position()=5] must become child::bk:para[attribute::type='warning'][position()=5]

Only the element names should be affected, the rest of the expression (functions, operators, values, etc.) should stay the same - or, if they do change, they should stay equivalent.

How can I achieve this?

While trying to solve this in C# I came across 2 different solutions, both of which are not good enough for my scenario:

Upvotes: 0

Views: 80

Answers (1)

Michael Kay
Michael Kay

Reputation: 163342

If you want this to work correctly on any XPath expression then there really isn't any alternative to parsing the expression against the XPath grammar. That's the only way, for example, that you can work out that the expression and and or or and needs to be converted to x:and and x:or or x:and. That's only overkill if you regard bug-free programs as an unaffordable luxury.

Upvotes: 2

Related Questions