Monday, February 13, 2012

Using Groovy to update/generate XML file


Recently when I refactored the Android framework in my work, I found I need to generate eclipse .classpath file based on the library file.
I found using Groovy XML library is a lot easier to do this job compare to Java.

1. Add a new library to the current .classpath file.
Problem:  You have a Eclipse .classpath file, which is XML, you need to add another jar file in the class path. for example, adding following into the .classpath:
<classpathentry kind="lib" path="libs/abc.jar"/>
view raw classpath item hosted with ❤ by GitHub
Solution:
def classpath = new XmlParser().parse('.classpath')
classpath.each {
println "${it.@kind} ${it.@path}"
}
def newEntry = new Node(classpath, 'classpathentry', [kind:'lib', path:'libs/abc.jar'])
println "after adding a new entry:"
classpath.each {
println "${it.@kind} ${it.@path}"
}
String outxml = groovy.xml.XmlUtil.serialize( classpath )
println outxml
 If you want to write the output to file, use the following code snippet:
def writer = new FileWriter(".classpath")
groovy.xml.XmlUtil.serialize( classpath,writer )

There is another method to print XML, using XmlNodePrinter, like:
new XmlNodePrinter().print(classpath)
view raw xmlnodeprinter hosted with ❤ by GitHub
But I found using XmlNodePrinter will not generate line break, and no xml header either.

2. Generate a new .classpath file
Problem:  iterate the libs folder, add all the jar file name into the .classpath file.
Solution:
def lib_folder = "libs";
def jarFiles = []
new File(lib_folder).eachFile { file ->
jarFiles << file.name
}
builder = new groovy.xml.StreamingMarkupBuilder()
builder.encoding = "UTF-8"
xmlDocument = builder.bind {
mkp.xmlDeclaration()
classpath {
classpathentry(kind:"src", path: "src")
classpathentry(kind:"src", path: "gen")
classpathentry(kind:"con", path: "com.android.ide.eclipse.adt.ANDROID_FRAMEWORK")
classpathentry(kind:"output", path: "bin")
jarFiles.each { file ->
classpathentry(kind:"lib", path: "libs/${file}")
}
}
}
def writer = new FileWriter(root + ".classpath")
groovy.xml.XmlUtil.serialize( xmlDocument, writer)

No comments:

Post a Comment