仅在 xslt 中的上下文中搜索关键字

问题描述 投票:0回答:1

我有一个 xml,其中有多个父节点。需要能够在每个父节点中搜索节点。必须使用 key 作为我的输入(在下面的示例中,jey 语句中的“4”)是从另一个节点动态派生的。如何将键查找的上下文设置为调用它的位置?

我的意见

<homes>
    <home>
        <to-reno>one</to-reno>
        <bedrooms name="master1">1</bedrooms>
        <bedrooms name="master2">2</bedrooms>
        <bedrooms name="master3">3</bedrooms>

    </home>
    <home>
        <to-reno>two</to-reno>
        <bedrooms name="master4">4</bedrooms>
        <bedrooms name="master5">5</bedrooms>
    </home>
</homes>

Xslt

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:key name="data-set" match="bedrooms" use="."/>
    
    <xsl:template match="*|@*">
        <xsl:copy>
            <xsl:apply-templates select="*|@*"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="home">
        <xsl:variable name="keyNode" select="key('data-set', '4')"/>
        <xsl:if test="$keyNode">
            <to-reno>
                <type>
                    <xsl:value-of select="to-reno"/>
                </type>
                <name>
                    <xsl:value-of select="$keyNode/@name"/>
                </name>
            </to-reno>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

电流输出

<homes>
    <to-reno>
        <type>one</type>
        <name>master4</name>
    </to-reno>
    <to-reno>
        <type>two</type>
        <name>master4</name>
    </to-reno>
</homes>

预期输出

<homes>
    <to-reno>
        <type>two</type>
        <name>master4</name>
    </to-reno>
</homes>
xslt-2.0
1个回答
1
投票

使用 key 函数的第三个参数传递您想要搜索的子树的根元素,因此在您的情况下,我认为您想要例如

<xsl:variable name="keyNode" select="key('data-set', '4', .)"/>

© www.soinside.com 2019 - 2024. All rights reserved.