【问题标题】:XSLT select all text except one child node textXSLT 选择除一个子节点文本之外的所有文本
【发布时间】:2013-08-02 11:27:15
【问题描述】:

我有这样的xml:

<article>
   <title> Test title - <literal> Compulsory - </literal> <fn> ABC </fn> 
   <comments> a comment</comments>
   </title>
</article>

我想在一个变量中获取所有子节点+自身文本 例如

$full_title = "考试题目 - 必修 - ABC"

cmets 节点文本除外。

以下是我错过标题节点文本的失败尝试。

<xsl:template name="test">
    <xsl:variable name="full_title" select="article/title/*[not(self::comments)][1]" />
    <xsl:variable name="width" select="45" /> 
                <xsl:choose>
                    <xsl:when test="string-length($full_title) &gt;    $width">
                        <xsl:value-of select="concat(substring($full_title,1,$width),'..')"/>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="$full_title"/>    
                    </xsl:otherwise>
            </xsl:choose>
</xsl:template>

【问题讨论】:

    标签: xslt select text nodes except


    【解决方案1】:

    * 更改为node()。这将选择作为&lt;title&gt; 元素的子元素的元素和文本节点。然后取出[1],因为你想要&lt;title&gt;所有个孩子:

    <xsl:variable name="full_title"
        select="string-join(article/title/node()[not(self::comments)], '')" />
    

    一种更可靠的方法,这样如果您在&lt;title&gt;&lt;comments&gt; 下有多个级别元素作为孙子出现,您就不会被绊倒,应该是这样:

    <xsl:variable name="full_title"
        select="string-join(article/title//text()[not(ancestor::comments)], '')" />
    

    更新:

    由于您希望变量保存一个字符串值,并且由于您将它传递给像 concat()string-length() 这样的函数,它们不能将多个节点的序列作为第一个参数,因此在周围使用 string-join(..., '')序列通过连接每个节点的字符串值将其转换为字符串。

    【讨论】:

    • 当我从“[not(self::cmets)][1]”中删除 [1] 时,我遇到了一个错误,同时使用 saxon 将 xml 转换为 html:错误:“更多的序列 的第一个参数不允许超过一个项目。这就是为什么我必须保留 [1],但结果我没有得到所有节点文本,有什么建议吗?
    • @Ali:好的,你说得对;我忘记了您使用$full_title 的方式。查看我的新编辑,使用string-join()
    【解决方案2】:

    试试这个:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
        <xsl:template match="/">
            <xsl:variable name="full-text">
                <xsl:apply-templates select="//*[not(self::comments)]" 
                   mode="no-comments"/> 
            </xsl:variable>
            <xsl:value-of select="$full-text"/><!-- just for debug-->
        </xsl:template >
    
        <xsl:template match="*" mode="no-comments">
            <xsl:value-of select="text()"/>
        </xsl:template>
    </xsl:stylesheet>
    

    mode 属性仅用于清楚说明

    【讨论】:

    • Dewfy,这将选择所有级别的文本节点,而不仅仅是 &lt;article&gt;&lt;title&gt; 内的节点。
    猜你喜欢
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多