Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT - Match variable element in predicate

Tags:

xslt

<xsl:apply-templates select="element[child='Yes']">

Works fine but I would like to use

<xsl:apply-templates select="element[$childElementName='Yes']">

so I can use a variable to specify the node.

For example

<xsl:apply-templates select="theList/entity[Central='Yes']">

works fine against:

<?xml version="1.0" encoding="utf-8"?>
<theList>
  <entity>
    <Business-Name>Company 1</Business-Name>
    <Phone-Number>123456</Phone-Number>
    <Central>Yes</Central>
    <region1>No</region1>
    <region2>Yes</region2>
    <region3>No</region3>
    <Northern>No</Northern>
  </entity>
  <entity>
    <Business-Name>Company 2</Business-Name>
    <Phone-Number>123456</Phone-Number>
    <Central>No</Central>
    <region1>Yes</region1>
    <region2>No</region2>
    <region3>No</region3>
    <Northern>Yes</Northern>
  </entity>
  <entity>
    <Business-Name>Company 3</Business-Name>
    <Phone-Number>123456</Phone-Number>
    <Central>Yes</Central>
    <region1>No</region1>
    <region2>No</region2>
    <region3>No</region3>
    <Northern>No</Northern>
  </entity>
  <entity>
    <Business-Name>Company 4</Business-Name>
    <Phone-Number>123456</Phone-Number>
    <Central>No</Central>
    <region1>No</region1>
    <region2>No</region2>
    <region3>No</region3>
    <Northern>No</Northern>
  </entity>
</theList>

But I do not wish to hard code the child element name.

Any suggestions?

Thanks Tim for the answer:

<xsl:apply-templates select="theList/entity[child::*[name()=$childElement]='Yes']" />
like image 625
John Hartley Avatar asked Jul 27 '10 06:07

John Hartley


2 Answers

You can test the name of an element using the local-name() function, like so

<xsl:apply-templates select="theList/entity[child::*[name()='Central']='Yes']" />

This checks all child nodes that have the name of 'Central'

You could then easily replace the hard-coding with a parameter or variable. Thus, if you use the following XSLT on your XML input:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="childElement">Central</xsl:param>
  <xsl:template match="/">
    <xsl:apply-templates select="theList/entity[child::*[name()=$childElement]='Yes']" />
  </xsl:template>
  <xsl:template match="entity">
    <Name><xsl:value-of select="Business-Name" /></Name>
  </xsl:template>
</xsl:stylesheet>

You would get the output

<Name>Company 1</Name><Name>Company 3</Name>
like image 196
Tim C Avatar answered Nov 16 '22 18:11

Tim C


Use:

theList/entity/*[name() = $childElementName][. = 'Yes']
like image 39
Dimitre Novatchev Avatar answered Nov 16 '22 18:11

Dimitre Novatchev