XPath – Common Mistake

When dealing with XPath, an extra forward slash (/) can make the difference between your application performing and making the decision that XPath just isn’t the solution for you.  So what is the difference between /Product and //Product?  Huge.

/Product means “go find the Product element that are my children”.  The engine only needs to look at child nodes relative to the current location.

//Product means “go find all of the Product elements that are a descendant of mine – I don’t care where they are at”.   This means that if your document is 50 levels deep, the engine will look through each and every one of them to find a product element.  If you have 10,000 elements to look through and then you have to go diving down the tree as well, it is obviously a more expensive than it needs to be.

Sometimes you don’t know where the element will reside in your XML document, so // makes sense.  However, if you know where you are looking, you should always use /.  Neither is “wrong”, but one can be a LOT more expensive than the other.

I’ve seen two XPath queries written today – one at work and one on the web, and both of them were using the inefficient double slash (//).  I hope this helps anybody who is doing any querying using XPath.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s