我正在尝试实现一个xsl,其中只有当该元素存在且具有某些值时,才会选择xml中的节点:
我做了一些研究,我发现这个表达式可用于测试条件:
<xsl:if test="/rootNode/node1" >
// whatever one wants to do
</xsl:if>
Run Code Online (Sandbox Code Playgroud)
它是否仅测试 - >/rootNode/node1的存在还是检查node1的内容?我们如何检查此表达式中node1的内容,它不应为null.
Tho*_*ler 10
以下转换应该可以帮助您处理所有情况.
如果内容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>
Run Code Online (Sandbox Code Playgroud)
您可以在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>
Run Code Online (Sandbox Code Playgroud)