Case insensitive xpath queries

I had an xpath query to test whether a node already exists in an xml document

Dim KeyphraseNode As XmlNode = xmlDoc.SelectSingleNode( _

String.Format("/websites/website[@url='{0}']/keyphrases/keyphrase[@value='{1}' and @type='{2}']" , _

WebsiteUrl, keyphrase.ToLower, keyphraseType))

Unfortunately users were testing for values with different capitalisations so the program was reporting that the nodes didn’t exist when actually they did.

I could have change the data in the xml file so that all data was stored as lowercase, but that would be nasty.

After a bit of digging round and consulting my trusty xpath book I found that there isn’t a nice and easy lowercase function built into xpath. And the best approach is to use the translate function. So the solution turned out to be

Dim KeyphraseNode As XmlNode = xmlDoc.SelectSingleNode( _

String.Format("/websites/website[@url='{0}']/keyphrases/keyphrase[translate(@value,

'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='{1}' and @type='{2}']", _

WebsiteUrl, keyphrase.ToLower, keyphraseType))

Hope that helps if anyone else needs to do a case insensitive xpath search.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.