使用XSLT实现CountryCode到CountryName的转换
根据CountryCode获取对应CountryName的XSLT实现方案
我来给你分享两种实用的实现方式,帮你快速根据XML里的CountryCode值替换成对应的国家名称:
方式一:用键值映射(适合多国家场景)
这种方式通过定义一个可维护的国家映射表,查询效率高,后续添加新国家也很方便。
示例XML输入
<Root> <User> <Name>John</Name> <CountryCode>USA</CountryCode> </User> <User> <Name>Li</Name> <CountryCode>CHN</CountryCode> </User> <User> <Name>Emma</Name> <CountryCode>GBR</CountryCode> </User> </Root>
完整XSLT代码
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <!-- 定义国家代码到名称的键映射 --> <xsl:key name="country-map" match="country" use="@code"/> <!-- 存储所有国家映射的变量,后续直接在这里加新国家就行 --> <xsl:variable name="country-data"> <country code="USA" name="United States"/> <country code="GBR" name="United Kingdom"/> <country code="CHN" name="China"/> <country code="FRA" name="France"/> <!-- 可以继续添加更多国家 --> </xsl:variable> <!-- 身份模板:复制原XML中所有未被特殊处理的节点和属性 --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <!-- 专门处理CountryCode节点,替换为CountryName --> <xsl:template match="CountryCode"> <CountryName> <!-- 查找对应名称,找不到就保留原代码 --> <xsl:value-of select="key('country-map', ., $country-data)/@name" default="."/> </CountryName> </xsl:template> </xsl:stylesheet>
代码说明
- 我们用
<xsl:key>建立了代码和名称的关联,把所有映射放在country-data变量里,维护起来特别方便,新增国家只需要加一行<country>标签。 - 身份模板保证原XML的结构和其他内容完全保留,只替换我们需要处理的
CountryCode节点。 - 如果遇到没有定义的国家代码,会自动保留原代码,避免出现空值。
方式二:分支匹配(适合少量国家场景)
如果你的国家映射不多,直接用<xsl:choose>分支判断更简洁,不需要额外定义键和变量:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <!-- 身份模板 --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <!-- 处理CountryCode节点 --> <xsl:template match="CountryCode"> <CountryName> <xsl:choose> <xsl:when test=". = 'USA'">United States</xsl:when> <xsl:when test=". = 'CHN'">China</xsl:when> <xsl:when test=". = 'GBR'">United Kingdom</xsl:when> <!-- 可以继续添加分支 --> <xsl:otherwise><xsl:value-of select="."/></xsl:otherwise> </xsl:choose> </CountryName> </xsl:template> </xsl:stylesheet>
这种写法简单直接,适合映射数量少的场景,缺点是国家多了之后代码会比较冗长。
内容的提问来源于stack exchange,提问作者Charlotte
相关产品推荐
相关产品推荐

