Reading a zip file from java using ZipInputStream
Java provides support for reading zip files in the form of ZipInputStream
. This class provides an API where you can
iterate over all the items in a given zip file, reading the data from the archive for each file.
In order to do this, first you must create the ZipInputStream
instance giving the file that you wish to
expand. Then you iterate using the getNextEntry
method on the stream, which returns the header data for
each entry in turn. Importantly this does not contain the data, which is actually read from the stream separately.
Reading XML in groovy using XmlParser
Groovy has great inbuilt xml support, and allows you to treat xml paths like objects. Reading elements and attributes is so straightforward that it was one of the factors that got me started with Groovy. So to build an object tree from xml, we just use the XmlParser
class.
To dereference an element we use normal dot syntax, for an attribute, simply add the at symbol (@) before the name, see the example below.
Write XML with GroovyBuilder
Groovy supports the concept of builders, which provide an abstraction between the required output content and the representation of it. Groovy supports this by providing a tree like structure in groovy code that represents the required HTML or XML:
import groovy.xml.MarkupBuilder
// create a builder to generate xml like content from a
// builder structure, in this case we choose
// StringWriter as the output, but it could be any writer.
def writer = new StringWriter();
def builder = new MarkupBuilder(writer);
builder.html {
head {
title "Hello world"
}
body {
h1 "My Hello world page"
p "This is the content"
}
}
println(writer);
So what have we done?
We generated some HTML, in this case we just printed it to the console, but we could have sent this back to a web browser for example, or saved it to disk. The XML structure that we generated from above looked as follows: