仅从父元素中修剪空白 [英] Trim whitespace from parent element only

查看:32
本文介绍了仅从父元素中修剪空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修剪 XML 中 p 标签内的前导空格,所以:

I'd like to trim the leading whitespace inside p tags in XML, so this:

<p>  Hey, <em>italics</em> and <em>italics</em>!</p>

变成这样:

<p>Hey, <em>italics</em> and <em>italics</em>!</p>

(修剪尾随空格不会有什么坏处,但这不是强制性的.)

(Trimming trailing whitespace won't hurt, but it's not mandatory.)

现在,我知道 normalize-whitespace() 应该这样做,但是如果我尝试将其应用于文本节点..

Now, I know normalize-whitespace() is supposed to do this, but if I try to apply it to the text nodes..

<xsl:template match="text()">
  <xsl:text>[</xsl:text>
  <xsl:value-of select="normalize-space(.)"/>
  <xsl:text>]</xsl:text>
</xsl:template>

...它单独应用于每个文本节点(在括号中)并将它们吸干:

...it's applied to each text node (in brackets) individually and sucks them dry:

[Hey,]<em>[italics]</em>[and]<em>[italics]</em>[!]

我的 XSLT 基本上是这样的:

My XSLT looks basically like this:

<xsl:template match="p">
    <xsl:apply-templates/>
</xsl:template>

那么有什么方法可以让 apply-templates 完成并然后在输出上运行 normalize-space,这应该做正确的事情?

So is there any way I can let apply-templates complete and then run normalize-space on the output, which should do the right thing?

推荐答案

此样式表:

<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:更好的表达(现在只有三个函数调用).

Edit 2: Better expression (now only three function calls).

编辑 3:匹配第一个后代文本节点(如果是文本节点,则不只是第一个节点).感谢@Dimitre 的评论.

Edit 3: Matching the first descendant text node (not just the first node if it's a text node). Thanks to @Dimitre's comment.

现在,有了这个输入:

<p><b>  Hey, </b><em>italics</em> and <em>italics</em>!</p>

输出:

<p><b>Hey, </b><em>italics</em> and <em>italics</em>!</p>

这篇关于仅从父元素中修剪空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆