如何用XSLT 1.0+xsl:import将XML的code元素替换为国家名称
解决方案
1. 示例文件结构
主XML(countries.xml)
<Countries> <Land> <code>CN</code> </Land> <Land> <code>US</code> </Land> <Land> <code>XX</code> </Land> </Countries>
外部代码映射XML(codelist.xml)
<CodeList> <Country> <code>CN</code> <name>中国</name> </Country> <Country> <code>US</code> <name>美国</name> </Country> <Country> <code>JP</code> <name>日本</name> </Country> </CodeList>
2. 正确的XSLT 1.0转换代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 定义key,用于快速匹配code对应的国家名称 --> <xsl:key name="country-by-code" match="Country" use="code"/> <!-- 加载外部代码列表XML --> <xsl:variable name="code-list" select="document('codelist.xml')/CodeList"/> <!-- 文本输出配置,如需RTF可修改method为"rtf" --> <xsl:output method="text" encoding="UTF-8"/> <xsl:template match="/"> <xsl:text>国家列表: </xsl:text> <xsl:apply-templates select="Countries/Land"/> </xsl:template> <xsl:template match="Land"> <xsl:variable name="current-code" select="code"/> <!-- 在外部code列表中查找匹配项 --> <xsl:variable name="matched-country" select="$code-list/key('country-by-code', $current-code)"/> <xsl:text>- </xsl:text> <xsl:choose> <xsl:when test="$matched-country"> <xsl:value-of select="$matched-country/name"/> </xsl:when> <xsl:otherwise> <xsl:text>Unknown</xsl:text> </xsl:otherwise> </xsl:choose> <xsl:text> </xsl:text> </xsl:template> </xsl:stylesheet>
3. 常见错误排查
错误1:误用xsl:import
xsl:import仅用于导入其他XSLT样式表,加载外部XML数据必须使用document()函数,这是你之前报错的核心原因。
错误2:外部文件路径问题
确保codelist.xml与主XML、XSLT文件在同一目录,或使用绝对路径(如document('C:/xml-files/codelist.xml'))。XML Notepad对相对路径的解析依赖于当前打开文件的位置,建议先将所有文件放在同一目录测试。
错误3:XML结构不匹配
检查codelist.xml的节点层级是否与XSLT中的路径一致(比如XSLT中用CodeList/Country/code,若你的外部XML结构不同,需调整match和use的路径)。
4. XML Notepad运行步骤
- 打开
countries.xml - 点击菜单栏Transform -> Apply XSLT
- 选择编写好的XSLT文件,点击Apply
预期文本输出:
国家列表: - 中国 - 美国 - Unknown
内容的提问来源于stack exchange,提问作者Tom Yeldim
相关产品推荐
相关产品推荐

