gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:16:07 24 4
gpt4 key购买 nike

我正在尝试实现一个 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>

关于xml - 如何使用 xsl :if 检查元素值是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33199562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com