我正在处理具有多个不同标签的XML。我正在匹配标签并将标签的值复制到新标签中。我对这个 xslt 只有一个问题。如果我正在处理的标记中不存在值信息,该怎么办?xslt 转换后我总是得到空文本标签。是否可以以某种方式避免这种情况,因此如果XML中不存在信息标记,则还将删除新的文本标记?希望我清楚我的问题是什么。感谢您的任何建议。
我的 XSLT:
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="test">
<text>
<xsl:apply-templates select="info/text()"/>
</text>
</xsl:template>
创建一个额外的模板来处理info
元素:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="test">
<xsl:apply-templates select="info"/>
</xsl:template>
<xsl:template match="info">
<text>
<xsl:apply-templates select="."/>
</text>
</xsl:template>
</xsl:stylesheet>
例如,在这个简单的输入上:
<r>
<test>
<info>blah</info>
</test>
<test></test>
</r>
将生成以下输出:
<r>
<text>blah</text>
</r>
您没有提供示例输入或输出,因此很难判断这是否正是您要查找的内容,但总体思路仍然存在。
您可以在模板的 match
属性中包含要求:只需添加谓词测试以检测文本节点是否存在。
test[info/text()]
仅当 test
元素具有名为 info
的子元素且其中包含非空文本节点时,上述 XPath 表达式才会匹配。
否则,您也可以使用 xsl:if
元素并测试文本节点是否存在。
<xsl:if test="info/text()">
<text>
<xsl:apply-templates select="info/text()"/>
</text>
</xsl>