Andrey Hihlovskiy
Professional blog on groovy, gradle, Java, Javascript and other stuff.
Tag Archives: XmlSlurper
A happier, groovier way to parse RTF: apache_tika + XmlSlurper
July 14, 2013
Posted by on 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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()}" | |
} | |
} | |
} |
Disappointment with groovy/XmlSlurper
July 10, 2013
Posted by on 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
July 5, 2013
Posted by on 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
Recent Comments