使用 XSLT 递归删除空的 xml 元素 [英] Remove empty xml elements recursively with XSLT
本文介绍了使用 XSLT 递归删除空的 xml 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从 xml 中递归删除空"元素(无子项、无属性或空属性).这是我拥有的 XSLT
I am trying to recursively remove 'empty' elements (no children, no attribute or empty attribute) from the xml. This is the XSLT I have
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[not(*) and
string-length(.)=0 and
(not(@*) or @*[string-length(.)=0])]">
<xsl:apply-templates/>
</xsl:template>
这是输入的 XML.我希望这个 XML 被转换为空字符串
This is the input XML. I expect this XML to be transformed to a empty string
<world>
<country>
<state>
<city>
<suburb1></suburb1>
<suburb2></suburb2>
</city>
</state>
</country>
</world>
但我得到了
<world>
<country>
<state/>
</country>
</world>
有人可以帮忙吗?我在论坛上研究了很多主题,但仍然没有运气.
Can anyone help? I've researched many threads in the forum but still no luck.
推荐答案
条件 not(*)
对于任何有子元素的元素都是假的——不管子元素包含什么.
The condition not(*)
is false for any element that has children - regardless of what the children contain.
如果您想修剪"不带果实"的任何树枝的树,请尝试:
If you want to "prune" the tree of any branches that do not carry "fruit", try:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*[descendant::text() or descendant-or-self::*/@*[string()]]">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@*[string()]">
<xsl:copy/>
</xsl:template>
</xsl:stylesheet>
这篇关于使用 XSLT 递归删除空的 xml 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文