编辑: [从字符替换开始,我最终在Dimitre Novatchev和Roland Bouman的帮助下发现了字符串替换
我认为示例代码足以解释要求..
这是示例 XML:
<root>
<node1>text node</node1>
<node2>space between the text</node2>
<node3> has to be replaced with $</node3>
</root>
这是我期待的输出:
<root>
<node1>text$node</node1>
<node2>space$between$the$text</node2>
<node3>$has$to$be$replaced$with$$</node3>
</root>
我尝试编写一个未显示所需输出的 XSLT 代码。
这是代码:
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()[.!='']">
<xsl:call-template name="rep_space">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
</xsl:template>
<xsl:template name="rep_space">
<xsl:param name="text"/>
<xsl:variable name="temp" select="'6'"/>
<xsl:choose>
<xsl:when test="contains(text,'2')">
<xsl:call-template name="rep_space">
<xsl:with-param name="text" select="concat((concat(substring-before(text,' '),temp)),substring-after(text,' '))"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
translate(., ' ', '$') 函数可以工作..但没有达到令人满意的程度..我的问题是..如果它是字符串而不是字符怎么办?我的意思是,假设我打算用“%20”替换''?还有一种情况,如果输入的 XML 不是“Pretty Print XML”,那么 XML 中出现的所有空格都被替换为 '$' ..
漂亮的打印 XML是具有适当缩进的文件,(通常我的输入 XML 从来没有这个)例如:
还有一个节点,这是@lower level
您可以观察到,节点之前没有“空格字符”<new> <test>
,但它们实际上是正确缩进的(使用 altova XMLSPY,我们可以在编辑菜单中给出一个简单的命令.. 将任何 XML 文件制作为“漂亮打印 XML”)..
如下例所示..
<new>
<test>one more node</test>
<test2>
<child>this is @ lower level</child>
</test2>
</new>
所有开始标签之前都有空格字符..<child>
标签之前的空格比<test2>
节点..
使用第二个示例 xml .. 所有空格字符都替换为 " %20
".. 因此输出将是 ..
<new>
%20%20<test>one%20more%20node</test>
%20%20<test2>
%20%20%20%20<child>this%20is%20@%20lower%20level</child>
%20%20</test2>
</new>
当然这不是预期的..
Dimitre Novatchev和Roland Bouman发布的解决方案还可以通过修改传递给被调用模板的参数来用另一个字符串替换一个字符串。
学习@Dimitre,@Roland 真是太棒了,我真的很感谢你们……
问候,
婴儿亲。