Converting XML to Flat Files with Groovy

Posted by Unknown Sunday, December 9, 2012 0 comments
Sunday November 11, 2012

Converting XML to Flat Files with Groovy

When integrating systems, you often need to convert data from one format to another. For example, you may receive data from a web service in XML and need to convert it to a flat file for a legacy system. It's usually not as simple as just moving data from a tag to a column either. There's often calculations and formatting required. Most often the code has the work of parsing, converting and formatting all mixed together. With a dynamic language like Groovy which has closures, we can abstract much of that work. For our example, we'll take a subset of the Microsoft sample books.xml file:


We would like to provided a mapping for each column that allows us to pull data out of the XML file and define the width of the column. We'll keep it simple to start with by assuming a fixed width flat file with all columns left justified. Following is a simple mapping using an array of maps:


Each closure should get a GPathResult to a "row" in the XML file. The closure should return the text that should go in the column. We'll need to supply the tag that identifies the tag in the XML file to pass to the closure. Following is an example test using our books data:


The implementation is fairly simple. We process each "tag" in the XML. For each mapping, we set the delegate for the closure to a map with the tag name and the GPathResults for that tag. The closure can then be executed to get the text for the column:


The above piece of code abstracts the processing into 8 lines of code. It is a testament to the power of a dynamic language that provides closures.

(2012-11-11 16:27:31.0) Permalink

View the original article here

THANK YOU FOR YOUR VISIT
Title: Converting XML to Flat Files with Groovy
Posted By Unknown
Blog Rating 5 dari 5
Hopefully this article useful to you. If you wish to quote, either part or all of the contents of this article please include a "dofollow links" to http://izone2.blogspot.com/2012/12/converting-xml-to-flat-files-with-groovy.html. Thank you for reading our articles and continue to follow this blog article.

0 comments:

Post a Comment

Trik SEO Terbaru support Online Shop Baju Wanita - Original design by Bamz | Copyright of Info Zone.