I created an xml using MarkupBuilder in groovy but how do i write it into a xml file in my project dir E:\tomcat 5.5\webapps\csm\include\xml
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
String[] splitted
xml.rows()
{ for(int i=0;i<lines.length-1;i++){
row()
{
for(int j=0;j<lines[i].length();j++)
{
splitted= lines[i].split(',');
}
name(splitted[0])
email(splitted[1])
}
}
}
here println writer.toString()
prints my whole xml content but i need it in a file in my tomcat project's xml
directory
Instead of using a StringWriter
, use a FileWriter
. Also use system property catalina.base
to get the Tomcat homepath.
def writer = new FileWriter(new File(System.getProperty("catalina.base") + "/webapps/csm/include/xml/yourfile.xml"))
Note however that it's not the best place to save your runtime generated files. They will be deleted every time you redeploy your .war
file.
Not to take away from the correct answers above, but you can make your code much more Groovy
:
new File( "${System.properties['catalina.base']}/webapps/csm/include/xml/yourfile.xml" ).withWriter { writer ->
def xml = new MarkupBuilder( writer )
xml.rows {
lines.each { line ->
row {
def splitted = line.split( ',' )
name( splitted[0] )
email( splitted[1] )
}
}
}
}
How about:
new File('E:\tomcat 5.5\webapps\csm\include\xml\Foo.xml') << writer.toString()
Not sure if you need to double escape \\
file path on windoze...
Instead of using a StringWriter
i used FileWriter
and as for the the path i did
def writer = new FileWriter("../webapps/csm/include/xml/data.xml" )
Finally this works :)
//class writer to write file
def writer = new StringWriter();
//builder xml
def xmlCreated = new MarkupBuilder(writer);
//file where will be write the xml
def fileXmlOut = new File("C:\\Users\\example\\Desktop\\example\\test.xml");
//method MarkupBuilder to xml
xmlCreated.mkp.xmlDeclaration(version: "1.0", encoding: "utf-8");
xmlCreated.playlist() {
list() {
//xml = your file xml parse
name xml.list.name.text()
}
eventlist () {
event(type: example.eventlist.@type)
}
}
//writing xml in file
fileXmlOut << writer.toString();