我想用另一个字符串替换另一个字符串。我找到了一个这样做的例子,但似乎不起作用。这是一个示例数据
<Addy>
<Row>
<LD>Dwelling, 1</D>
<LN> East</LN>
<L>1</L>
<Tf>Abesinia Passage</Tf>
</Row>
<Row>
<LD>Logde</LD>
<LN>North </LN>
<L>1</L>
<Tf>Abesinia Passage</Tf>
</Row>
</Addy>我想用这种方式替换下面的字符串。
Dwelling = FLAT
Lodge = SHOP下面是我使用的代码。它只删除了LD元素中的所有值。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:lookup="lookup">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<lookup:data>
<LD code="Dwelling">FLAT</LD>
<LD code="Lodge">SHOP</LD>
</lookup:data>
<xsl:variable name="lookup" select="document('')/*/lookup:data"/>
<xsl:template match="LD/text()">
<xsl:value-of select="$lookup/LD[@code = current()]" />
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>如果应用于上面的输入数据,它会产生以下结果:
<Addy>
<Row>
<LD></LD>
<LN> East</LN>
<L>1</L>
<Tf>Abesinia Passage</Tf>
</Row>
<Row>
<LD></LD>
<LN>North </LN>
<L>1</L>
<Tf>Abesinia Passage</Tf>
</Row>
</Addy>使用适当的代码应产生预期结果
<Addy>
<Row>
<LD>FLAT,1</D>
<LN> East</LN>
<L>1</L>
<Tf>Abesinia Passage</Tf>
</Row>
<Row>
<LD>SHOP</LD>
<LN>North </LN>
<L>1</L>
<Tf>Abesinia Passage</Tf>
</Row>
</Addy> 发布于 2012-09-11 07:58:54
现有代码的问题是这一行
<xsl:value-of select="$lookup/LD[@code = current()]" />只有当有一个LD元素的文本等于上下文节点的整个文本时,才会发出任何内容。因此,谓词需要使用contains()而不是=。
使用XSLT 2.0,您可以按如下方式更改此模板:
<xsl:template match="LD/text()">
<xsl:variable name="LD" select="$lookup/LD[contains(current(), @code)]" />
<xsl:value-of select="replace(., $LD/@code, $LD/text())" />
</xsl:template>如果不能使用XSLT2.0,可以使用EXSLT str:replace()而不是XSLT2.0版本。
这假设code属性值不包含任何在正则表达式中会被特殊解释的特殊字符,如.、$等。
它还假设任何LD/text()节点中不会出现超过一段代码。
https://stackoverflow.com/questions/12360735
复制相似问题