Andrey Hihlovskiy

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

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:


package org.akhikhl.test
import org.apache.tika.metadata.Metadata
import org.apache.tika.parser.rtf.RTFParser
class ParseRtf {
def parse(String rtfText) {
// not validating, not ns-aware
XmlSlurper slurper = new XmlSlurper(false, false)
InputStream rtfStream = new ByteArrayInputStream(value.getBytes())
new RTFParser().parse(rtfStream, slurper, new Metadata())
slurper.document.'body'.p.each { p ->
println "Got paragraph: ${p.text()}"
}
}
}

view raw

ParseRtf.groovy

hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: