使用 XSL 替换 XML 中的部分字符串 [英] Replace part of a string in XML using XSL

查看:38
本文介绍了使用 XSL 替换 XML 中的部分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 xml:

<links url="../servlet/SearchServlet?query=contact&filter=&sort=relevance&sortdir=desc&col=5&startdate=0&enddate=0&xsl=xml&page=">

<link page="date" url="../servlet/SearchServlet?query=contact&filter=&sort=date&col=5&startdate=0&enddate=0&page=1&xsl=xml"/>

我正在使用这个 xsl 来转换链接:

I am using this xsl to transform the links:

 <xsl:for-each select="//link">

            <xsl:choose>
                <xsl:when test="@page='next'">
                    <xsl:text></xsl:text>
                    <a href="{@url}">&gt;&gt;</a>
                </xsl:when>
                <xsl:when test="@page='prev'">
                    <a href="{@url}">&lt;&lt;</a>
                    <xsl:text></xsl:text>
                </xsl:when>

                <xsl:when test="@page='date'"/>
                <xsl:when test="@page='relevance'"/>
                <xsl:when test="@page='alpha'"/>

            </xsl:choose>
        </xsl:for-each>

现在棘手的部分是我想替换 ../servlet/SearchServlet../search 链接中的部分 url代码>

The tricky part now is I want to replace part of the url in the link from ../servlet/SearchServlet to ../search

我如何实现这一目标?我试过使用这个模板,但它取代了整个网址.

How do I achieve this? I tried using this template but it replaces the whole url.

推荐答案

<xsl:template match="link/@url">
  <xsl:param name="search"  select="'../servlet/SearchServlet'" />
  <xsl:param name="replace" select="'../search'" />
  <xsl:attribute name="href">
    <xsl:choose>
      <xsl:when test="contains(., $search)">
        <xsl:value-of select="concat($replace, substring-after(., $search))" />
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="." />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:attribute>
</xsl:template>

调用

<a>
  <xsl:apply-templates select="@url" />
  <xsl:text>&lt;&lt;</xsl:text>
</a>

请注意,您可以选择使用

Note that you could optionally use

<xsl:apply-templates select="@url" />
  <xsl:with-param name="search"  select="'xyz'" />
  <xsl:with-param name="replace" select="'foo'" />
</xsl:apply-templates>

提供不同的搜索/替换值.

to supply different search/replace values.

这篇关于使用 XSL 替换 XML 中的部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆