我有一个Node,我希望null
在将它写入文件之前从递归中删除所有属性和空子.我在下面的工作,但似乎应该有一个内置的方法.我错过了什么吗?
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 }
tim_yates.. 6
我知道没有用于执行此操作的构建方法...您可以将代码缩小(并递归删除空子代码),如下所示:
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 = '''| | '''.stripMargin()- |
| | || | woo |
| || |- hi
|
我们可以解析它并清理它并打印出来:
Node root = new XmlParser().parseText( xml ) cleanNode( root ) println XmlUtil.serialize( root )
这使:
woo
- hi
如您所见,整个块已被清理,因为它不包含任何信息.
我知道没有用于执行此操作的构建方法...您可以将代码缩小(并递归删除空子代码),如下所示:
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()
我们可以解析它并清理它并打印出来:
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>
块已被清理,因为它不包含任何信息.