检查父项是否在其子项之外包含文本

时间:2014-02-05 10:44:17

标签: xslt xpath

我有一个类似于这个的XML:

<parent>
    <child>child's text</child>
    <child>other child's text</child>
    parent's text
</parent>

请注意,它允许有多个子元素。

我想知道父元素是否在其子元素之外有文本。

我想出了这个解决方案:

<xsl:if test="normalize-space(parent/child[1]) = normalize-space(parent)">
    <xsl:text>No parent text</xsl:text>
</xsl:if>

我使用parent/child[1]因为normalize-space函数不接受序列作为它的参数。

有更好的方法吗?

(我发现this有关该主题的问题,但答案不正确或问题不同)

2 个答案:

答案 0 :(得分:1)

使用text()明确引用文本节点。

更好的方法是:

<xsl:if test="parent/text()[not(parent::child)]">
  <!--This parent element has text nodes-->
</xsl:if>

否则,你可以写一个单独的模板:

<xsl:template match="text()[parent::parent]">
   <xsl:text>parent element with text nodes!</xsl:text>
</xsl:template>

答案 1 :(得分:1)

此模板:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
<xsl:strip-space elements="*"/>    
    <xsl:template match="/">
        <xsl:choose>
            <xsl:when test="parent/child::text()">
                true
            </xsl:when>
            <xsl:otherwise>false</xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

应用于输入XML时,返回

true

应用于以下XML时:

<?xml version="1.0" encoding="UTF-8"?>
<parent>
    <child>child's text</child>
    <child>other child's text</child>
</parent>

返回

false
相关问题