【发布时间】:2010-02-23 12:40:51
【问题描述】:
编辑: [从字符替换开始 最后我发现了字符串 在 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 中的所有空间 替换为 '$' ..
Pretty print XML 是具有适当缩进的文件,(通常我的输入 XML 从来没有这个)例如:
多一个节点 这是@较低级别
您可以观察到,<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,我真的很感激 谢谢你们..
问候,
婴儿专业人士。
【问题讨论】:
-
又是一个好问题。我不明白关于“Pretty Print XML”的那部分——请您详细说明一下吗?最好是另一个输入和输出示例。
-
程序员:xml 是否在一行中并不重要——如果它只有空白节点,我的解决方案将删除所有节点。如果您所说的实际上没有纯空白文本节点,那么 xsl:strip-space 指令将什么也不做——在这种情况下它是无害的。我提供的解决方案更通用——它适用于两种情况:只有空白节点和没有空白节点时。