David Thielen
David Thielen

Reputation: 33026

How can I test for a valid index

It is legal to have XPath that is "/root/name[bogus = 'dave']" where the bogus node does not exist. It will return null on a SelectSingleNode.

But XPath that is "/root/name[5]" where there are only 4 name nodes under root throws an exception. (At least it does in .NET).

What is a good way to test and see if an index value is valid?

thanks - dave

Upvotes: 0

Views: 60

Answers (1)

LarsH
LarsH

Reputation: 28004

In XPath 1.0, you could evaluate this XPath expression:

bool(/root/name[5])

which will return true if the <root> element has a fifth <name> child.

But as others have said, XPath itself should not raise an exception for trying to access a node that doesn't exist. However, the .NET library may raise an exception if you try to dereference a null value.

Upvotes: 1

Related Questions