如何在XSLT中通过预定义键值对动态填充表格列:将国家名称映射为对应城市
解决方案:用XSLT实现国家到首都的动态映射
要解决表格中城市列显示国家名称的问题,我们可以用两种XSLT方案实现国家到首都的自动替换——没有匹配映射时保留原国家名称,两种方法分别适配不同的场景:
方法一:用<xsl:key>构建可扩展的映射表
如果后续需要添加更多国家-首都配对,这种方法的可维护性更好,适合映射项较多的场景。
修改后的完整XSLT代码
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 定义国家到首都的键值映射规则 --> <xsl:key name="country-to-capital" match="capital" use="@country"/> <!-- 内置的国家-首都映射表,可随时添加新项 --> <xsl:variable name="capitals"> <capital country="USA">Washington D.C.</capital> <capital country="UK">London</capital> <!-- 示例:新增映射 <capital country="France">Paris</capital> --> </xsl:variable> <xsl:template match="/"> <html> <body> <h2>Sample Transformation</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Id</th> <th>Name</th> <th>City</th> </tr> <!-- 遍历XML中的cd节点(注意移除了原代码中多余的en:命名空间,适配你的数据源) --> <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="id"/></td> <td><xsl:value-of select="name"/></td> <td> <!-- 执行映射逻辑 --> <xsl:variable name="current-country" select="country"/> <xsl:variable name="matched-capital" select="key('country-to-capital', $current-country, $capitals)"/> <xsl:choose> <xsl:when test="$matched-capital"> <xsl:value-of select="$matched-capital"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="$current-country"/> </xsl:otherwise> </xsl:choose> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
代码说明:
- 用
<xsl:key>定义映射规则,把country属性和首都文本关联起来; - 用
<xsl:variable>维护一个可扩展的映射表,新增配对只需添加新的<capital>节点; - 在城市列处理逻辑中,先获取当前国家名称,再通过
key()函数查找对应首都:找到就显示首都,找不到则保留原国家名。
方法二:用<xsl:choose>做简单条件判断
如果你的映射项很少(比如只有两三个),直接用条件判断会更简洁:
城市列的代码片段替换
<td> <xsl:choose> <xsl:when test="country='USA'">Washington D.C.</xsl:when> <xsl:when test="country='UK'">London</xsl:when> <!-- 可添加更多判断项 --> <xsl:otherwise><xsl:value-of select="country"/></xsl:otherwise> </xsl:choose> </td>
额外提示:
原代码中的en:命名空间在你的XML数据源中并未使用,所以我移除了该前缀以确保节点匹配正常。如果你的实际业务XML确实包含命名空间,需要在XSLT中正确声明并对应使用。
内容的提问来源于stack exchange,提问作者Anam Qureshi
相关产品推荐
相关产品推荐

