<xsl:apply-templates select="element[child='Yes']">
工作正常,但我想使用
<xsl:apply-templates select="element[$childElementName='Yes']">
因此我可以使用变量来指定节点。
例如
<xsl:apply-templates select="theList/entity[Central='Yes']">
适用于:
<?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>
但是我不希望对子元素名称进行硬编码。
有什么建议么?
感谢蒂姆的答案:
<xsl:apply-templates select="theList/entity[child::*[name()=$childElement]='Yes']" />
最佳答案
您可以使用local-name()函数测试元素的名称,如下所示
<xsl:apply-templates select="theList/entity[child::*[name()='Central']='Yes']" />
这将检查所有名称为“Central”的子节点
然后,您可以轻松地用参数或变量替换硬编码。因此,如果在XML输入上使用以下XSLT:
<?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>
您将获得输出
<Name>Company 1</Name><Name>Company 3</Name>
关于XSLT-谓词中匹配变量元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3341122/