如何用xsl:apply-templates筛选匹配外部XML类的property节点
解决方法
你的代码存在两个核心问题:一是拼写错误,二是key()函数的使用方式不符合XSLT 2.0规范,以下是修正后的实现方案:
1. 修正基础拼写错误
你写的<xsl:apply-template>缺少末尾的s,正确标签应为<xsl:apply-templates>,这是语法层面的硬性错误。
2. 正确使用key()函数实现匹配
前提假设
假设index.xml的结构为类名称直接作为节点文本:
<classes> <class>User</class> <class>Product</class> </classes>
属性文档结构示例:
<properties> <property type="User" name="userId"/> <property type="Order" name="orderNum"/> <property type="Product" name="prodName"/> </properties>
完整XSLT代码
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 定义索引key:匹配index.xml中的class节点,用节点文本作为键值 --> <xsl:key name="class-lookup" match="class" use="."/> <!-- 加载外部index.xml文档 --> <xsl:variable name="index-doc" select="document('index.xml')"/> <xsl:template match="/"> <!-- 仅选择type值存在于index.xml的property节点 --> <xsl:apply-templates select="properties/property[key('class-lookup', @type, $index-doc)]"/> </xsl:template> <!-- 处理匹配到的property节点 --> <xsl:template match="property"> <processed-property> <xsl:copy-of select="@*"/> </processed-property> </xsl:template> </xsl:stylesheet>
关键说明
key()函数的第三个参数必须指定外部文档节点($index-doc),确保查找上下文是index.xml而非当前文档- 如果
index.xml中的类是通过属性存储的(比如<class type="User"/>),只需把key定义改为:<xsl:key name="class-lookup" match="class" use="@type"/>
3. 替代方案:直接节点查找(适合小型数据集)
如果数据集不大,也可以不用key(),直接通过节点路径判断,逻辑更直观:
<xsl:variable name="index-doc" select="document('index.xml')"/> <xsl:apply-templates select="properties/property[$index-doc/classes/class[. = current()/@type]]"/>
内容的提问来源于stack exchange,提问作者Ben Pyton
相关产品推荐
相关产品推荐

