Thanks Paulo! The remove of XmlParser is working.
But, for an xml like bellow after first run, we end up with enother empty node
<qux/>. Only the leaf empty nodes were getting removed.
final def EXAMPLE = """
<foo>
   <bar>Bar</bar>
   <baz></baz>
   <xpto></xpto>
   <qux>
       <boo></boo>
   </qux>
</foo>
"""
I modified it as follows:
final def EXAMPLE = """
<foo>
   <bar>Bar</bar>
   <baz></baz>
   <xpto></xpto>
   <qux>
       <boo></boo>
   </qux>
</foo>
"""
def records = new XmlParser().parseText (EXAMPLE)
def cleanUpNode( node ) {
   println node
   def childs = node.children()
  Â
   def remove = []
   childs.each {
       if (it instanceof Node) {
          Â
           if ( !it.children()) {              Â
               remove.add it Â
           } else {
               cleanUpNode it
               if(!it.children()) {
                   remove.add it
               }
           }
       }
   }
  Â
   remove.each { node.remove( it ) }
}
cleanUpNode records
new XmlNodePrinter( preserveWhitespace: true ).print( records )
Cheers!
Tridib
________________________________
From: Paulo Gabriel Poiati <paulogpoiati-***@public.gmane.org>
To: user-i9PBDF1N6cxnkHa44VUL00B+***@public.gmane.org
Sent: Fri, June 24, 2011 3:19:48 PM
Subject: Re: [groovy-user] GPathResult : Removing XML node
Hello Tribid,Â
I think it's easy to use XmlParser for this task.
EX:
final def EXAMPLE = """
<foo>
   <bar>Bar</bar>
   <baz></baz>
   <xpto></xpto>
   <qux>
     <zoo>123</zoo>
     <boo></boo>
   </qux>
</foo>
"""
def records = new XmlParser().parseText EXAMPLE
def cleanUpNode( node ) {
   println node
   def childs = node.children()
   def remove = []
   childs.each {
     if ( it instanceof Node ) {
       if ( !it.children() ) {
         remove.add it Â
       }
       cleanUpNode it
     }
   }
  Â
   remove.each { node.remove( it ) }
}
cleanUpNode records
new XmlNodePrinter( preserveWhitespace: true ).print( records )
âI added the nodes to a collection before removing because of a
ConcurrentModificationException that would occur.
[]'s
Paulo Poiati
blog.paulopoiati.com
On Fri, Jun 24, 2011 at 6:26 PM, Tridib Samanta <***@yahoo.com> wrote:
Hi Experts,
Post by Tridib SamantaI am frustrated after 3-4 hours of effort and failed to remove a xml node. :(.
Is not there a simple remove() method to remove xml node???
 void cleanUpNode(GPathResult node) {
       if(node) {
           GPathResult children = node.children()
           children.each { child->
               cleanUpNode(child)
           }
          Â
         def childrenCount = node.children().size()
            if(!value) {
               if(childrenCount == 0) {
                 node.parent().remove(node) --->>. This does not work
               }
           }
       }
   }
Please HELP!
Thanks
Tridib