【问题标题】:How to remove some content from the elements using XSLT如何使用 XSLT 从元素中删除一些内容
【发布时间】:2017-04-24 14:24:38
【问题描述】:

对于图像标签,我只需要在 JSON 输出中使用 XSLT 保留带有“file/”内容的图像文件:

我的输入 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 处理器?
  • version="2.0" @Michael

标签: json xml xslt


【解决方案1】:

在 XSLT 2.0 中,您可以:

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

【讨论】:

    【解决方案2】:

    要在最后一次出现字符(在本例中为“/”)之后获取字符串,您需要(在 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 模板的灵感来自 this SO post

    【讨论】:

    • 这也可以正常工作@ZX485。我跟着下面的。感谢您的代码。
    猜你喜欢
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2013-12-12
    • 1970-01-01
    相关资源
    最近更新 更多