Welcome to MSDN Blogs Sign in | Join | Help

Getting the POSITION() of the PARENT node using Xpath

I just spent waaaaaay too long figuring this out, so I'll leave a note of it for future projects:

To enumerate the current node's position in the current nodeset, position() is great.  However when using nested nodesets, getting the parent's position relative to its nodeset is a bit more complex:

count(parent::*/preceding-sibling::*) + 1 - assuming all nodes in the parent nodeset are of the same type, otherwise:

count(parent::*/preceding-sibling::<type>) + 1 where <type> is the type of the parent node

A quick beakdown:

  • parent::* - selects the parent of the current node
  • parent::*/preceding-sibling::* - selects the nodes which precede the parent in its nodeset
  • count(parent::*/preceding-sibling::*) - counts the nodes preceding the parent
  • count(parent::*/preceding-sibling::*) + 1 - if there are n nodes before the parent, then the parent is # n+1
Published Wednesday, September 08, 2004 2:12 AM by Addys
Filed under: ,

Comments

# re: Getting the POSITION() of the PARENT node using Xpath

Wednesday, September 08, 2004 2:51 AM by Teemu
Yeah,

pretty much same as:

count(../preceding-sibling::node()) + 1

Checking for type is reasonable to avoid counting whitespace nodes.

Great post!

# Addy Santo Rocks!

Wednesday, November 03, 2004 2:08 PM by Pick A Bar
For the second time in the last month I've bumped into a problem, googled it, clicked on a link to Addy's blog, and found the perfect solution. Getting the POSITION() of the PARENT node using Xpath XmlDocument.CreateProcessingInstruction goes better with...

# Santomania Getting the POSITION of the PARENT node using Xpath | Outdoor Ceiling Fans

# Santomania Getting the POSITION of the PARENT node using Xpath | Cast Iron Cookware

# Santomania Getting the POSITION of the PARENT node using Xpath | alternative dating

New Comments to this post are disabled
 
Page view tracker