Forum Discussion
pflaumengeist
13 years agoContributor
Well this code is messy, but it does the job
This will read in files from D:\books, in my case fantasy.txt and science.fiction.txt
fantasy.txt contains this lines
science.fiction.txt contains this lines
and will output
for fantasy.txt
for science.fiction.txt
import java.io.File;
import static groovy.io.FileType.*;
def sortByTypeThenNameFile = {a, b -> a.isFile() != b.isFile() ? a.isFile() <=> b.isFile() : b.name.toLowerCase() <=> a.name.toLowerCase()};
new File('D:/books/').traverse(
type : FILES,
sort : sortByTypeThenNameFile) {
file ->
log.info 'reading file ' + file
log.info createXML(file)
}
def createXML(file) {
//create root xml
def xml = new XmlParser().parseText('<root/>')
file.eachLine {
line ->
//add "book" node
xml.appendNode('book')
if(line.split(';').size() > 1) {
//[xml.book.size() -1] is for the newest node
xml.book[xml.book.size() -1].appendNode('author', line.split(';')[0])
xml.book[xml.book.size() -1].appendNode('title', line.split(';')[1])
}
}
def w = new StringWriter()
def p = new XmlNodePrinter(new PrintWriter(w))
p.preserveWhitespace = true;
p.print(xml)
return w.toString();
}
This will read in files from D:\books, in my case fantasy.txt and science.fiction.txt
fantasy.txt contains this lines
Piers Anthony;A Spell for Chameleon
Piers Anthony;The Source of Magic
Piers Anthony;Castle Roogna
science.fiction.txt contains this lines
Douglas Noel Adams;The Hitchhiker’s Guide to the Galaxy
Peter Ackroyd;Milton in America
Peter Ackroyd;The Clerkenwell Tales
Isaac Asimov;The Caves of Steel
Isaac Asimov;Foundation
and will output
for fantasy.txt
<root>
<book>
<author>Piers Anthony</author>
<title>A Spell for Chameleon</title>
</book>
<book>
<author>Piers Anthony</author>
<title>The Source of Magic</title>
</book>
<book>
<author>Piers Anthony</author>
<title>Castle Roogna</title>
</book>
</root>
for science.fiction.txt
<root>
<book>
<author>Douglas Noel Adams</author>
<title>The Hitchhiker’s Guide to the Galaxy</title>
</book>
<book>
<author>Peter Ackroyd</author>
<title>Milton in America</title>
</book>
<book>
<author>Peter Ackroyd</author>
<title>The Clerkenwell Tales</title>
</book>
<book>
<author>Isaac Asimov</author>
<title>The Caves of Steel</title>
</book>
<book>
<author>Isaac Asimov</author>
<title>Foundation</title>
</book>
</root>