Andrey Hihlovskiy

Professional blog on groovy, gradle, Java, Javascript and other stuff.

Category Archives: xml

Groovy DSL == thermonuclear way of writing XML

import groovy.xml.MarkupBuilder

String createEAD(Closure closure) {
  def writer = new StringWriter()
  def xml = new MarkupBuilder(writer)
  xml.mkp.xmlDeclaration(version: '1.0', encoding: 'UTF-8')
  xml.'ead:ead'('xmlns:ead': 'urn:isbn:1-931666-22-9') {
    closure.delegate = new Object() {
      def text(Map attrs, content) {
        def a = attrs.keySet().find { it in ['bold', 'italic', 'underline'] }
        if(a && attrs[a]) {
          xml.'ead:emph' render: a, {
            text attrs.findAll({ it.key != a }), content
          }
        } else
          text content
      }
      def text(content) {
        if(content instanceof String)
          xml.mkp.yield content
        else if(content instanceof Closure)
          content()
      }
    }
    closure()
  }
  return writer.toString()
}

println createEAD {
  text bold: true, italic: true, {
    text 'Hello, '
    text underline: true, 'world!'
  }
}

expected output:

<?xml version='1.0' encoding='UTF-8'?>
<ead:ead xmlns:ead='urn:isbn:1-931666-22-9'>
  <ead:emph render='bold'>
    <ead:emph render='italic'>Hello, 
      <ead:emph render='underline'>world!</ead:emph>
    </ead:emph>
  </ead:emph>
</ead:ead>

A happier, groovier way to parse RTF: apache_tika + XmlSlurper

I discovered a new, easier way to parse RTF in java/groovy programs. Consider the following sequence:

1. Instantiate XmlSlurper

2. Instantiate RTFParser (of Apache Tika)

3. Parse RTF (either file or string), passing XmlSlurper to RTFParser (such passing is possible, because RTFParser expects ContentHandler interface, which is implemented by XmlSlurper).

4. Traverse RTF content groovy-style: each, find, findAll, etc.

The example:

Disappointment with groovy/XmlSlurper

Greatest disappointment with groovy/XmlSlurper: it does not read/interpret XML comments. Quite critical for massive XML processing/transformations, when it is necessary to keep change delta to minimum.
In the last project I had to recede to JDOM2 – it reads, interprets and writes XML comments without problems. Sad, volume of code doubles compared to XmlSlurper.

groovy XmlParser and XmlSlurper

I am absolutely astonished by functionality of groovy classes XmlParser and XmlSlurper. The both are similar to each other, with one important difference: XmlParser is more DOM-like (all data in memory), while XmlSlurper is more SAX-like (data parsing delayed until needed).
The most charming thing is how both work together with closures, regexps and collection methods. I am seriously thinking about shifting all XML-specific code to these facilities.

http://groovy.codehaus.org/Reading+XML+using+Groovy%27s+XmlParser

http://groovy.codehaus.org/Reading+XML+using+Groovy%27s+XmlSlurper