【问题标题】:Using XSLT 1.0 apply-templates only on certain attribute values仅对某些属性值使用 XSLT 1.0 应用模板
【发布时间】:2013-06-17 15:15:29
【问题描述】:

我试图避免使用此解决方案的程序性方法,但我不确定这是否可行。

这是我的 XML:

<countData>
<count countId="37" name="Data Response 1">
    <year yearId="2013">
        <month monthId="5">
            <day dayId="23" countVal="6092"/>
            <day dayId="24" countVal="6238"/>
            <day dayId="27" countVal="6324"/>
            <day dayId="28" countVal="6328"/>
            <day dayId="29" countVal="3164"/>
        </month>
            <day dayId="23" countVal="7000"/>
            <day dayId="24" countVal="7000"/>
            <day dayId="27" countVal="7000"/>
            <day dayId="28" countVal="7000"/>
            <day dayId="29" countVal="7000"/>
        </month>
    </year>
</count>
<count countId="39" name="Data Response 2">
    <year yearId="2013">
        <month monthId="5">
            <day dayId="23" countVal="675"/>
            <day dayId="24" countVal="709"/>
            <day dayId="27" countVal="754"/>
            <day dayId="28" countVal="731"/>
            <day dayId="29" countVal="377"/>
        </month>
    </year>
</count>

我想为所有 37 或 39 的 count/@countIds 应用模板(在此示例中)。这是我所在的位置:

    <xsl:template match="/">

    <xsl:apply-templates mode="TimeFrame"/>

</xsl:template>

<xsl:template match="*" mode="TimeFrame">

    <xsl:if test="count[@countId=37] or count[@countId=39]">
        <magic>Only hitting this once for countId 37</magic>
    </xsl:if>

</xsl:template>

我将有很多带有“模式”的模板,因为我正在以多种不同的方式处理相同的响应。

不确定我是如何错过“范围”匹配而只获得 1 个。

我确定这与我的“程序性思维”有关。 :)

在这方面的任何帮助都会很棒!

谢谢,

【问题讨论】:

    标签: xslt conditional xslt-1.0 apply-templates


    【解决方案1】:

    您的主模板 &lt;xsl:template match="/"&gt; 只运行一次 - 即用于 &lt;countData&gt; 元素。

    这意味着你要么忘记了递归:

    <xsl:template match="*" mode="TimeFrame">
    
        <xsl:if test="count[@countId=37] or count[@countId=39]">
            <magic>Only hitting this once for countId 37</magic>
        </xsl:if>
    
        <xsl:apply-templates mode="TimeFrame"/> <!-- ! -->
    
    </xsl:template>
    

    ...或者您未能为主模板设置正确的上下文:

    <xsl:template match="/countData"><!-- ! -->
    
        <xsl:apply-templates mode="TimeFrame"/>
    
    </xsl:template>
    
    <!-- or, alternatively -->
    
    <xsl:template match="/">
    
        <xsl:apply-templates select="countData/*" mode="TimeFrame"/>
    
    </xsl:template>
    

    【讨论】:

    • 我的问题是我试图在开始遍历子节点之前评估“countId”值。在模板 mode="TimeFrame" 中添加 apply-templates select = "*" 会强制递归在这些子项中发生。我真的只想对作为 x、y、z 值的“countID”进行“匹配”,然后处理它们的子节点。
    • 实际上,在尝试听取您的建议后,我出现了一个错字。这完全符合我的要求。非常感谢!
    猜你喜欢
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 2018-01-21
    • 2019-05-01
    • 1970-01-01
    相关资源
    最近更新 更多