从节点中删除空属性并清空子节点 [英] Remove null attributes and empty children from Node

查看:140
本文介绍了从节点中删除空属性并清空子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个节点,我想删除所有 null 属性,并在我将其写入文件之前递归地清空子项。我在下面的工作,但它似乎应该有一个内置的方法。我错过了什么?

I have a Node which I want to remove all null attributes and empty children from recursively before I write it to a file. What I have below works, but it seems like there should be a built in method for this. Have I missed something?

Node cleanNode(Node node) {

    // Find null attributes
    def attributesToRemove = []
    for(e in node.attributes()) {
        if(e.value == null) {
            attributesToRemove.add(e.key)
        }
    }

    // Remove null attributes
    for(attribute in attributesToRemove) {
        node.attributes().remove(attribute)
    }

    // Clean this node's children
    for(child in node.children()) {
        if(child instanceof Node) {
            cleanNode(child)
        }
    }

    // If node has no attributes, no children, and no text then discard it by setting it to null
    if(!node.attributes() && !node.children() && !node.text()) {
        node = null
    }

    node
}


推荐答案

r这样做,我知道...你可以让你的代码稍微小一些(并递归地删除空的孩子),如下所示:

There's not a build in method for doing this that I know of... You could get your code a little smaller (and recursively remove empty children) like so:

boolean cleanNode( Node node ) {
    node.attributes().with { a ->
        a.findAll { !it.value }.each { a.remove( it.key ) }
    }
    node.children().with { kids ->
        kids.findAll { it instanceof Node ? !cleanNode( it ) : false }
            .each { kids.remove( it ) }
    }
    node.attributes() || node.children() || node.text()
}

所以给了xml:

def xml = '''<root>
            |  <head>
            |    <item>
            |       <woo/>
            |    </item>
            |  </head>
            |  <body att=''>
            |    <h1 name='' title='title'>
            |      woo
            |    </h1>
            |  </body>
            |  <tail>
            |    <item>hi</item>
            |  </tail>
            |</root>'''.stripMargin()

我们可以解析它并打印出来并打印出来:

We can parse it and clean it and print it out:

Node root = new XmlParser().parseText( xml )
cleanNode( root )
println XmlUtil.serialize( root )

给出:

<?xml version="1.0" encoding="UTF-8"?><root>
  <body>
    <h1 title="title">woo</h1>
  </body>
  <tail>
    <item>hi</item>
  </tail>
</root>

正如您所见,整个< head> block已被清除,因为它不包含任何信息。

As you can see, the whole <head> block has been cleaned as it contained no information.

这篇关于从节点中删除空属性并清空子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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