javaxmlgroovymarkupbuilder

How to write xml into a file using MarkupBuilder


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


Solution

  • 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.