我目前正在使用XSL 2.0将XML对象传输到HTML。我的XML中的一个字段是国家/地区的ID。国家/地区代码的id-label映射在另一个XML(countries.xml)中定义,如:
<countries>
<country id="1" name="United States of America"/>
<country id="2" name="Canada"/>
</countries>
是否可以在我的主XSL转换中加载countries.xml并获取我的id的国家/地区标签?
答案 0 :(得分:0)
是的,使用doc()
或document()
函数打开XML文件并构建节点树。这些函数返回创建的树的根节点,然后从那里获取信息。
为了完整性,您的代码看起来如下所示,假设您正在查找变量$findCode
中找到的值,您在XSLT 2.0中只需要一个声明和一行:
<xsl:key name="countries" match="country" use="@id"/>
...other code...
<xsl:value-of select="key('countries',$findCode,document('countryCodes.xml'))/@name"/>
答案 1 :(得分:0)
使用&lt; xsl:apply-templates select =“”mode =“”&gt;
找到解决方案我创建了一个单独的countries.xsl文件,如下所示,并使用&lt; xsl:call-template name =“countrySubstitution”&gt;调用它。
在我的主要XSL中:
<xsl:template match="country">
<xsl:call-template name="countrySubstitution">
<xsl:with-param name="contextName" select="@name"/>
</xsl:call-template>
</xsl:template>
countries.xsl:
<xsl:stylesheet version="2.0">
<xsl:template name="countrySubstitution">
<xsl:param name="countryCode" select="."/>
<xsl:apply-templates select="document('countries.xml')" mode="ABCD">
<xsl:with-param name="countryCode" select="@id"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="/" mode="ABCD">
<xsl:param name="countryCode" select="."/>
<xsl:value-of select="//country[@id=$countryCode]/@name" />
</xsl:template>
</xsl:stylesheet>