Nate Reed
Nate Reed

Reputation: 7011

How can I shorten this xpath expression?

I have defined a variable called tags which selects a node set of elements whose names are one of several values:

<xsl:variable name="tags" select="//xs:element[@name='Subscription' or @name='Account' or @name='Product'  or @name='ProductRatePlan' or @name='ProductRatePlanCharge' or @name='Usage']"/>

I would like to define a variable as such:

<xsl:variable name="tagNames" select="'Subscription','Account','Product','ProductRatePlan','ProductRatePlanCharge','Usage'/>

How could I rewrite the first expression to select all the nodes whose names are in the set $tagNames? In essence, I'm looking for an operation that is analagous to a SQL set membership:

SELECT * FROM tags WHERE name in ('Subscription', 'Account', 'Product'....)

Upvotes: 1

Views: 803

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

One way to do this:

//xs:element
  [contains('|Subscription|Account|Product|ProductRatePlan|ProductRatePlanCharge|Usage|',
            concat('|', @name, '|'))]

So, you can have a variable or parameter:

<xsl:variable name="vTags"
 select="'|Subscription|Account|Product|ProductRatePlan|ProductRatePlanCharge|Usage|'"/>

and your main XPath expression becomes:

//xs:element[contains($vTags, concat('|', @name, '|'))]

Upvotes: 1

Michael Kay
Michael Kay

Reputation: 163282

In XPath 2.0 you can write:

<xsl:variable name="tags" select="//xs:element[@name=('Subscription','Account','Product','ProductRatePlan','ProductRatePlanCharge','Usage')]"/>

Upvotes: 2

Related Questions