[英]How to get an attribute on the ancestor axis in XSLT
我有 xml:
<msg id="abc" type="test">
<local id="def"/>
<cnts x:type="fld" id="111" type="a2">
</cnts>
</msg>
xslt 是:
<xsl:template match="contents[@x:type='fld']">
<xsl:variable name="msgs">
<xsl:for-each select="ancestoer::msg">
<msg><xsl:value-of select="@type"/></msg>
</xsl:for-each>
</xsl:variable>
</xsl:template>
我希望輸出是:
<msg>test</msg>
但它沒有按預期工作。 有人可以幫忙嗎?
您的 XSLT 和 XML 有幾個問題,每個問題可能是也可能不是問題的原因:
contents
(您的意思是cnts
嗎?)。xsl:stylesheet
元素中,也無法編譯, ancestoer::msg
將引發編譯時(靜態)錯誤。msg
,不確定這是故意的如果以上所有內容在您的實際 XSLT 中都是正確的,那么您的問題就出在其他地方,我們將不得不查看更多的 XSLT和XML,事實上,我們需要一個最小、完整和可驗證的示例。
也就是說,以下是使用祖先軸的三種方式:
<xsl:value-of select="ancestor::msg/@type" />
。如果要遍歷所有祖先,可以使用:
<xsl:template match="contents[@x:type='fld']"> <xsl:apply-templates select="ancestor::msg" mode="anc" /> </xsl:template> <xsl:template match="msg" mode="anc"> <msg><xsl:value-of select="@type" /></msg> </xsl:message>
在這個例子中,我故意切換模式,因為很有可能你已經在其他地方匹配了msg
,在這種情況下你可能會陷入一個永無止境的循環。
xsl:for-each
。 這並沒有錯,只是不那么靈活,從長遠來看,打字更多。 不需要使用變量,但如果您想使用變量,只需確保您也使用它,例如使用xsl:copy-of
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.