How to write xml into a file using MarkupBuilder

2019-07-11 14:05发布

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

5条回答
对你真心纯属浪费
2楼-- · 2019-07-11 14:42

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.

查看更多
爷、活的狠高调
3楼-- · 2019-07-11 14:43

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] )
      }
    }
  }
}
查看更多
劫难
4楼-- · 2019-07-11 14:48

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

查看更多
女痞
5楼-- · 2019-07-11 14:55

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 :)

查看更多
等我变得足够好
6楼-- · 2019-07-11 14:56
//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();
查看更多
登录 后发表回答