Xml xslt-递归空节点清理
我正在尝试清理一个具有任意元素名称的文件,该名称如下所示:Xml xslt-递归空节点清理,xml,xslt,Xml,Xslt,我正在尝试清理一个具有任意元素名称的文件,该名称如下所示: <root> <nodeone> <subnode blah="1" blah2="abc" /> </nodeone> <nodeone> <subnode>with other stuff</subnode> </nodeone> <nodeone>
<root>
<nodeone>
<subnode blah="1" blah2="abc" />
</nodeone>
<nodeone>
<subnode>with other stuff</subnode>
</nodeone>
<nodeone>
<subnode />
</nodeone>
</root>
<root>
<nodeone>
<subnode blah="1" blah2="abc" />
</nodeone>
<nodeone>
<subnode>with other stuff</subnode>
</nodeone>
</root>
还有其他东西
放入一个如下所示的文件:
<root>
<nodeone>
<subnode blah="1" blah2="abc" />
</nodeone>
<nodeone>
<subnode>with other stuff</subnode>
</nodeone>
<nodeone>
<subnode />
</nodeone>
</root>
<root>
<nodeone>
<subnode blah="1" blah2="abc" />
</nodeone>
<nodeone>
<subnode>with other stuff</subnode>
</nodeone>
</root>
还有其他东西
您可以看到,所有具有空子级的“nodeone”都消失了,但是任何具有内部内容或非空属性的
都被保留下来
我目前尝试的解决方案是:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[not(normalize-space()) and not(@*)]"/>
</xsl:stylesheet>
这将删除任何内部内容为空的节点并保留属性,但也会从输出中删除
文本,这不是所需的结果。您正在匹配的元素名称为任何既没有文本内容也没有属性的元素。因此,这也与您的
元素相匹配。试试这个:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="nodeone[*[not(normalize-space())][not(@*)]]"/>
</xsl:stylesheet>
如果您想要通用解决方案,请尝试此模板
<xsl:template match="*[not(normalize-space()) and not(.//@*)]"/>
在这里,
/*
将检查当前元素(正在匹配)和所有后代元素的属性。顺便说一句,如果您想删除无子女的节点一个元素(即
),那么改用
。对,正如我刚才所说的,这是一个包含任意节点的文档。我不一定知道它们被称为什么,但是如果它们是空的并且没有包含属性的内容,我希望从输出中省略它们。重点是,我不能创建像您提供的那样选择特定节点的结构。这有意义吗?所以
的名称总是nodeone,但是
可能有不同的名称?为了反映这一点,我修改了上面的答案。