如何使用 xsl:if 检查元素值是否为空

How to check if an element value is null using xsl:if

我正在尝试实现一个 xsl,其中来自 xml 的节点只有在该元素存在且具有某些值时才会被选中:

我做了一些研究,我发现这个表达式可以用于测试条件:

<xsl:if test="/rootNode/node1" >

 // whatever one wants to do   

</xsl:if>

它会只测试 --> /rootNode/node1 的存在还是同时检查 node1 的内容?我们如何检查这个表达式中 node1 的内容,它不应该为空。

以下转换应该可以帮助您处理所有情况。

如果node1的内容是文字,可以用text()来检测。如果内容是任意元素,可以用*检测。要检查它是否为空,可以添加条件not(node())。如果要在 node1 本身不存在的情况下执行操作,请向根节点添加 not(node1) 条件。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/rootNode/node1/text()">
has text
</xsl:template>
<xsl:template match="/rootNode/node1/*">
has elements
</xsl:template>
<xsl:template match="/rootNode/node1[not(node())]">
is empty
</xsl:template>
<xsl:template match="/rootNode[not(node1)]">
no node1
</xsl:template>
</xsl:stylesheet> 

您可以在 xsl:if 个节点中应用相同的方法:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/rootNode">
        <xsl:if test="node1/text()">
        has text
        </xsl:if>
        <xsl:if test="node1/*">
        has elements
        </xsl:if>
        <xsl:if test="node1[not(node())]">
        is empty
        </xsl:if>
        <xsl:if test="not(node1)">
        no node1
        </xsl:if>
    </xsl:template>
</xsl:stylesheet> 

Will it test for the existence of --> /rootNode/node1 only or check the contents of node1 as well?

这是一个存在性测试。

How does we check the contents of node1 in this expression that it should not be null.

如果元素存在,则不能为空。但是,它可以是 空。 对于元素,这意味着它没有子元素。