我想在XML中修剪p标记内的前导空格,所以如下所示:
<p> Hey, <em>italics</em> and <em>italics</em>!</p>变成这样:
<p>Hey, <em>italics</em> and <em>italics</em>!</p>(修整尾随空格不会有什么害处,但这不是强制性的。)
现在,我知道normalize-whitespace()应该这样做,但是如果我试图将它应用于文本节点..
<xsl:template match="text()">
<xsl:text>[</xsl:text>
<xsl:value-of select="normalize-space(.)"/>
<xsl:text>]</xsl:text>
</xsl:template>.它分别应用于每个文本节点(括号中),并将它们吸干:
[Hey,]<em>[italics]</em>[and]<em>[italics]</em>[!]我的XSLT基本上如下所示:
<xsl:template match="p">
<xsl:apply-templates/>
</xsl:template>那么,有什么方法可以让应用模板完成,然后在输出上运行规范化空间,这应该是正确的吗?
发布于 2010-10-22 13:11:34
这个样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p//text()[1][generate-id()=
generate-id(ancestor::p[1]
/descendant::text()[1])]">
<xsl:variable name="vFirstNotSpace"
select="substring(normalize-space(),1,1)"/>
<xsl:value-of select="concat($vFirstNotSpace,
substring-after(.,$vFirstNotSpace))"/>
</xsl:template>
</xsl:stylesheet>输出:
<p>Hey, <em>italics</em> and <em>italics</em>!</p>编辑2:更好的表达式(现在只有三个函数调用)。
编辑3:匹配第一个子代文本节点(如果是文本节点,则不只是第一个节点)。感谢@Dimitre的评论。
现在,有了这个输入:
<p><b> Hey, </b><em>italics</em> and <em>italics</em>!</p>输出:
<p><b>Hey, </b><em>italics</em> and <em>italics</em>!</p>发布于 2010-10-22 11:26:22
我会这样做:
<xsl:template match="p">
<xsl:apply-templates/>
</xsl:template>
<!-- strip leading whitespace -->
<xsl:template match="p/node()[1][self::text()]">
<xsl:call-template name="left-trim">
<xsl:with-param name="s" value="."/>
</xsl:call-template>
</xsl:template>这将从<p>元素的初始节点子节点(如果是文本节点)中剥离左空间。如果它不是第一个节点子节点,它不会从第一个文本节点子节点中剥夺空间。例如在
<p><em>Hey</em> there</p>我故意避免从“那里”的前面删除空间,因为这会使在浏览器中呈现的单词一起运行。如果您确实想要删除该空间,请将匹配模式更改为
match="p/text()[1]"如果您还想去掉尾随空格(正如标题可能暗示的那样),请添加以下两个模板:
<!-- strip trailing whitespace -->
<xsl:template match="p/node()[last()][self::text()]">
<xsl:call-template name="right-trim">
<xsl:with-param name="s" value="."/>
</xsl:call-template>
</xsl:template>
<!-- strip leading/trailing whitespace on sole text node -->
<xsl:template match="p/node()[position() = 1 and
position() = last()][self::text()]"
priority="2">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>左修剪和右修剪模板的定义位于XSLT的Trim模板 (未经测试)。对于包含大量<p>的文档,它们可能比较慢。
<xsl:value-of select="replace(.,'^\s+','')" />和
<xsl:value-of select="replace(.,'\s+$','')" />(多亏了普里西拉·沃尔姆斯利。)
发布于 2010-10-22 04:40:36
你想要
<xsl:template match="text()">
<xsl:value-of select=
"substring(
substring(normalize-space(concat('[',.,']')),2),
1,
string-length(.)
)"/>
</xsl:template>它将字符串包装在"[]"中,然后执行normalize-string(),然后最后删除包装字符。
https://stackoverflow.com/questions/3993896
复制相似问题