XSL 递归忽略空子级 [英] XSL Ignore Empty Children Recursively

查看:23
本文介绍了XSL 递归忽略空子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在清理一些冗长的 XML 时尝试了一些古怪的方法,即递归删除所有空节点.

Trying something kind of wacky in cleaning up some verbose XML, which is to remove all empty nodes recursively.

为此,我认为一个节点是空"的,如果它有(a)没有子节点,(b)只有空白内容,(c)只有空"子节点.也就是说,我认为以下是空的",因为所有的叶子都是空的/只有空白的节点:

For this purpose, I consider a node to be "empty" if it has (a) no child nodes, (b) whitespace-only content, (c) only "empty" child nodes. That is, I consider the following to be "empty" because all of the leaves are empty/whitespace-only nodes:

<foo>
  <bar>
    <baz/>
  </bar>
  <quux>  </quux>
</foo>

我尝试在模板中使用 <xsl:if test="child::node()"> ,但这似乎不起作用.完全有可能的答案是自己走树,傻",但似乎 XSL 应该能够做的事情?

I tried using <xsl:if test="child::node()"> in my templates, but that didn't seem to work. It's entirely possible the answer is "walk the tree yourself, silly", but it seems like the sort of thing XSL should be able to do?

我希望

<foo>
  <bar>
    <baz/>
  </bar>
  <quux>  </quux>
  <quuux>Actual content</quuux>
</foo>

回来

<foo>
  <quuux>Actual content</quuux>
</foo>

我想到了这个过滤器.

推荐答案

child::node() 对您不起作用的原因是因为您确实在那里有子节点 - 它们'重新空白文本节点.相反,尝试类似 normalize-space() != '' 的方法.你可能也不想要 if 那里,或者 - 把它放在 match 代替:

The reason why child::node() didn't work for you was because you do have child nodes there - they're whitespace text nodes. Instead, try something like normalize-space() != ''. You probably don't want an if there, either - put it in match instead:

<xsl:template match="node() | @*">
  <xsl:copy>
    <xsl:apply-templates select="node() | @*"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="*[normalize-space() = '']"/>

这篇关于XSL 递归忽略空子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆