Vivian River
Vivian River

Reputation: 32400

How to use XSLT to match nodes where an attribute falls in a range of values specified by a variable?

In my XSLT, I have a collection of nodes called MyProducts with each node having a ProductId node.

I want to read another node called ProductCatalog that contains a list of product Ids and then select only the products from MyProducts that have a product Id in ProductCatalog.

To that end, I've written an XSLT variable that gets the valid Ids:

<xsl:variable name="ValidIds" select="ProductCatalog/ProductId" />
<xsl:variable name="MyProductsWithValidId" select="ProductCatalog(... />

I think there ought to be some function I can complete this XSLT with that specifies that I want only nodes from ProductCatalog where the ProductId is contained in the ValidIds variable.

How do I do this? My XSLT engine is running XSLT-2.0

Upvotes: 1

Views: 94

Answers (1)

G. Ken Holman
G. Ken Holman

Reputation: 4403

<xsl:variable name="MyProductsWithValidId" select="ProductCatalog[ProductId=$ValidIds]"/>

In XSLT 1 and XSLT 2 you can compare with multiple values on either side of the =. The processor checks each of one side with each of the other, and as soon as any comparison is true() the result true() is returned. false() is only returned when all possible comparisons have been made.

So you will know that either none of the comparisons are true, or at least one of the comparisons is true, but you won't know which one or ones.

A formal way in XSLT 2 is to say:

<xsl:variable name="MyProductsWithValidId" 
              select="ProductCatalog[some $v in $ValidIds satisfies ProductId=$v]"/>

... but I prefer just using the = myself.

Upvotes: 3

Related Questions