簡體   English   中英

XSLT替換刪除html標簽

[英]XSLT replace remove html tags

為什么函數replace()刪除變量的html標簽?

我有兩個變量:

    <xsl:variable name="content1">
        <xsl:apply-templates select="." mode="my-mode">
        </xsl:apply-templates>
    </xsl:variable>
    <xsl:variable name="content2">
        <xsl:copy-of select="$content1, 'a', 'b')" />
    </xsl:variable>

$content1有html標簽, $content2沒有,為什么?

當定義一個函數對字符串進行操作時,如果您將其傳遞給節點,則它將節點“霧化”(提取其內容)以創建函數所需的字符串。 這將刪除有關該節點的其他信息,例如其名稱。 (請注意,在將源文檔解析為節點樹時,標記本身已被刪除。)

我想你可能打算寫

<xsl:variable name="content2">
    <xsl:copy-of select="replace($content1, 'a', 'b')" />
</xsl:variable>

請注意,這最好寫成

<xsl:variable name="content2" select="replace($content1, 'a', 'b')"/>

避免了從字符串到文本節點的反復轉換再返回到字符串的重復轉換的成本。

在不確切知道源文件是什么的情況下,很難准確建議您應如何編寫此代碼。 如果$ content是具有簡單文本內容且沒有屬性的元素,則最簡單的可能是

<xsl:variable name="content2">
    <xsl:apply-templates select="$content1" mode="replace"/>
</xsl:variable>

<xsl:template match="*" mode="replace">
  <xsl:copy>
    <xsl:value-of select="replace(., 'a', 'b')" />
  </xsl:copy>
</xsl:template>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM