使用XSLT 1.0,XSLT 2.0的正则表达式方法通常不可用.是否有任何非正则表达式替换源xml文档中节点中的多个字段,例如转换: ?xml version="1.0" encoding="utf-8"?xliff xmlns:xliff="urn:oasis:names:tc:xliff:do
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns:xliff="urn:oasis:names:tc:xliff:document:1.1" version="1.1">
<file>
<source>abc [[field1]] def [[field2]] ghi</source>
</file>
</xliff>
至:
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns:xliff="urn:oasis:names:tc:xliff:document:1.1" version="1.1">
<file>
<source>abc F def F ghi</source>
</file>
</xliff>
I. XSLT 1.0解决方案:
这种转变:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pTargetStart" select="'[['"/>
<xsl:param name="pTargetEnd" select="']]'"/>
<xsl:param name="pReplacement" select="'F'"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="source/text()" name="replace">
<xsl:param name="pText" select="."/>
<xsl:param name="pTargetStart" select="$pTargetStart"/>
<xsl:param name="pTargetEnd" select="$pTargetEnd"/>
<xsl:param name="pRep" select="$pReplacement"/>
<xsl:choose>
<xsl:when test=
"not(contains($pText, $pTargetStart)
and
contains($pText, $pTargetEnd)
)
or
not(contains(substring-after($pText, $pTargetStart),
$pTargetEnd
)
)
">
<xsl:value-of select="$pText"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="substring-before($pText, $pTargetStart)"/>
<xsl:value-of select="$pRep"/>
<xsl:variable name="vremText" select=
"substring-after(substring-after($pText, $pTargetStart),
$pTargetEnd
)"/>
<xsl:call-template name="replace">
<xsl:with-param name="pText" select="$vremText"/>
<xsl:with-param name="pTargetStart" select="$pTargetStart"/>
<xsl:with-param name="pTargetEnd" select="$pTargetEnd"/>
<xsl:with-param name="pRep" select="$pRep"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
当应用于提供的XML文档时:
<xliff xmlns:xliff="urn:oasis:names:tc:xliff:document:1.1" version="1.1">
<file>
<source>abc [[field1]] def [[field2]] ghi</source>
</file>
</xliff>
产生想要的,正确的结果:
<xliff xmlns:xliff="urn:oasis:names:tc:xliff:document:1.1" version="1.1">
<file>
<source>abc F def F ghi</source>
</file>
</xliff>
II. XSLT 2.0解决方案(仅供比较):
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="source/text()"> <xsl:sequence select="replace(., '\[\[(.*?)\]\]', 'F')"/> </xsl:template> </xsl:stylesheet>
