[英]XSLT1.0 - Replace string in a XML document
我有一个XML文档,我想使用XSLT 1.0替换一些特殊的子字符串。 我不能使用替换功能(仅适用于XSLT 2.0)。 由于这个原因,我找到了一个替代解决方案(模板string-replace-all ),我正在尝试使用它……但是没有成功。 这是XML的示例:
<parent>
<child1>hello world!</child1>
<child2>example of text</child2>
</parent>
我想用“家伙”代替“世界”。 我有这个xslt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns="urn:hl7-org:v2xml" xmlns:hl7="urn:hl7-org:v2xml" exclude-result-prefixes="hl7">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<!--Identity template, copia tutto in uscita -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template name="string-replace-all">
<xsl:param name="text" />
<xsl:param name="replace" />
<xsl:param name="by" />
<xsl:choose>
<xsl:when test="$text = '' or $replace = '' or not($replace)" >
<!-- Prevent this routine from hanging -->
<xsl:value-of select="$text" />
</xsl:when>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)" />
<xsl:value-of select="$by" />
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text,$replace)" />
<xsl:with-param name="replace" select="$replace" />
<xsl:with-param name="by" select="$by" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="text()" >
<xsl:variable name="newtext">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="." />
<xsl:with-param name="replace" select="world" />
<xsl:with-param name="by" select="guys" />
</xsl:call-template>
</xsl:variable>
</xsl:template>
</xsl:stylesheet>
输出是
<parent>
<child1/>
<child2/>
</parent>
调用string-replace-all
被设置到从未使用过的变量newtext
中。
只需从template match="text()"
删除<xsl:variable name="newtext">
和</xsl:variable>
。
并且还要查看@ hr_117的答案:如果要用guys
替换字符串world
,则必须将其放入'
。 否则,将搜索元素world
。
例如:
<xsl:template match="text()" >
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="." />
<xsl:with-param name="replace" select="'world'" />
<xsl:with-param name="by" select="'guys'" />
</xsl:call-template>
</xsl:template>
您需要将template参数更改为字符串。
尝试:
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="." />
<xsl:with-param name="replace" select="'a'" />
<xsl:with-param name="by" select="'A'" />
</xsl:call-template>
没有单引号select="a"
正在寻找元素a
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.