Solved

groovy/grails viewing xml example

Posted on 2011-03-11
2
474 Views
Last Modified: 2013-11-13
From this code example from the book "Grails in Action", how would i print the actual formatted XML?  Do I use file.txt?
import groovy.xml.MarkupBuilder
import groovy.util.XmlSlurper

def file = new File ("test.xml")
def objs = [
[quantity:10, name:"Orange",type:"Fruit"],
[quantity:6, name:"Apple",type:"Fruit"],
[quantity:2, name:"Chair",type:"Furniture"]]
def b = new MarkupBuilder(new FileWriter(file))
b.root{
  objs.each{o ->
    item(qty:o.quantity) {
      name(o.name)
      type(o.type)
      }
      }
      }
 def xml = new XmlSlurper().parse(file)
 assert xml.item.size()==3
 assert xml.item[0].name =="Orange"
 assert xml.item[0].@qty == "10"
 println "Fruits:${xml.item.findAll{it.type=='Fruit'}*.name}"
 println "Total:${xml.item.@qty.list().sum{it.toInteger()}}"

Open in new window

0
Comment
Question by:melodi_roberts
2 Comments
 
LVL 3

Accepted Solution

by:
wannabetechie earned 250 total points
ID: 35512048
You can print the xml from the XmlSlurper like this

println XmlUtil.serialize(xml)

Open in new window


If you want to print directly from the MarkupBuilder then you need to pass StringWriter to the constructor.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now