dramblys
dramblys

Reputation: 23

XPath: select node based on other node's value

Suppose I have a list of items, each with its own <id> element. There is also a <primaryId> element (outside mentioned list) specifying which one of these items is 'primary'. How do I select 'primary' item's <value> element? Is it possible to do using XPath in .Net?

The result in the following example should be <value>val2</value>.

<root>
  <primaryId>2</primaryId>
  <items>
    <item>
      <id>1</id>
      <value>val1</value>
    </item>
    <item>
      <id>2</id>
      <value>val2</value>
    </item>
  </items>
</root>

Upvotes: 2

Views: 2734

Answers (2)

ThW
ThW

Reputation: 19482

Location paths in XPath can include conditions in [].

So first select the primary id node:

/root/primaryId

Make it a condition, compare it with the id element in the context of the condition:

[id=/root/primaryId]

Use it to filter the item nodes:

/root/items/item[id=/root/primaryId]

And the complete expression:

/root/items/item[id=/root/primaryId]/value

Upvotes: 4

Rudolf Yurgenson
Rudolf Yurgenson

Reputation: 603

<xsl:value-of select="/root/items/item[id=/root/primaryId]/value"/>

Upvotes: -1

Related Questions