簡體   English   中英

如何使用XSLT從元素中刪除一些內容

[英]How to remove some content from the elements using XSLT

對於圖像標簽,我需要使用JSON輸出中的XSLT僅保留具有“文件/”內容的圖像文件:

我的輸入XML文件是:

<image>binary/alias/my.jpg</image>

XSL用作:

<xsl:template match="image">
  image: <xsl:apply-templates/>,
</xsl:template>

我得到的JSON輸出是:

image: binary/alias/my.jpg

我需要的輸出為:

image: files/my.jpg

請幫我。 提前致謝。

在XSLT 2.0中,您可以執行以下操作:

<xsl:template match="image">
    <xsl:text>image: files/</xsl:text>
    <xsl:value-of select="tokenize(., '/')[last()]"/>
</xsl:template>

要在最后一次出現字符(在本例中為“ /”)之后獲取字符串,您需要(在XSLT-1.0中)一個遞歸模板。 應用此模板,解決方案很簡單:輸出所需的前綴文本'image:files /'並附加遞歸模板的結果:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="image">
    image: files/<xsl:call-template name="LastOccurrence">
      <xsl:with-param name="value" select="text()" />
      <xsl:with-param name="separator" select="'/'" />
    </xsl:call-template>
  </xsl:template> 

  <xsl:template name="LastOccurrence">
    <xsl:param name="value" />
    <xsl:param name="separator" select="'/'" />

    <xsl:choose>
      <xsl:when test="contains($value, $separator)">
        <xsl:call-template name="LastOccurrence">
          <xsl:with-param name="value" select="substring-after($value, $separator)" />
          <xsl:with-param name="separator" select="$separator" />
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$value" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

LastOccurrence模板是受此SO帖子啟發的。

暫無
暫無

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

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