Tuesday 2 April 2013

Groovy Xml Series: Printing Xml

I started reviewing my knowledge of Groovy's xml capabilities due to an entry in the Groovy user's mailing list.

Somebody asked about how to print a GPath query result. Because I knew about the GPath API, I suggested to start building the output from the available methods, I mean, if you had a Node / GPathResult (Depending on the parser you used to parse the xml: XmlParser/XmlSlurper respectively) representing

value

You could print that node with the following statement:

println "<${node.name()}>${node.text()}</{node.name()}>"


But luckily somebody mentioned we could be doing the same thing using groovy.xml.XmlUtil class. It has several static methods to serialize the xml fragment from several type of sources (Node,GPathResult,String...)

Thus I've added a sample to my xmlgroovy project at Github to remember how I can for example print out the result of a GPath result. This is a slightly changed version in order to execute it on the GroovyConsole:

       

import groovy.xml.XmlUtil

def xml = """
                                                                                                            
                       
                       
                   
                   Don Xijote       
                   Manuel De Cervantes
                       
                   
                   Catcher in the Rye
                  JD Salinger
                      
                  
                 Alice in Wonderland
                  Lewis Carroll
                      
                   
                  Don Xijote       
                  Manuel De Cervantes
              
          
                     
  
"""
 
   def response = new XmlParser().parseText(xml)
   def nodeToSerialize = response.'**'.find{it.name() == 'author'}
   def nodeAsText = XmlUtil.serialize(nodeToSerialize)

   println nodeAsText

In this example I'm parsing the xml and and printing out only the author's node I was interested in. And it looks like:
Manuel De Cervantes

Missing

  • XmlNodePrinter : If you are using Node instances because you've parsed the document with XmlParser you can use XmlNodePrinter. You can check out the entry of MrHaki's blog where he covered the topic.

No comments:

Post a Comment