The previous article describes how to parse an XML file using groovy, and this article describes how to generate an XML file. Like parsing XML, groovy also offers two ways to Markupbuilder and Streamingmarkupbuilder. Generally speaking, Streamingmarkupbuilder is more professional and more complete in function. Their differences are somewhat similar to Dom and sax, which means that processing large XML files is better than streamingmarkupbuilder performance, but in general, there is little difference. Here we take markupbuilder as an example.
Code
Import Groovy.xml.MarkupBuilder class XmlWriter {public static main (Def args) {def strxml = new StringWriter
() markupbuilder MB = new Groovy.xml.MarkupBuilder (strxml); MB. '? XML ' (Version: "1.0", Encoding: "UTF-8") mb.interview{data{person (ID: "05891", Comments:
"Social recruitment") {title{position (code: "P7", "Staff SE")
Age (' Assessment ') (Interviewer: "Manager1", "Tech is OK") experience{phase (from: "A", To: "Now", "CompanyA") phase (from: "2010", To: "A", "Companyb")}} person (ID: "05892", Comments: "Campus Recrui
Tment ") {title{position (code:" P6 "," SE ")} Age ("assessment") (Interviewer: "MaNager2 "," Tech is OK ") experience{phase (from:" A ", To:" Now "," Universitya ")
Phase (from: "A", To: ""), "Companyb")}} interviewinfo{date ("2016-10-12") address ("Meetingroom 402") or
Ganizator (Dept: "Cloud", "Zhangsan")}} print strxml def xmlFile = "Output.xml" PrintWriter pw = new PrintWriter (xmlFile) Pw.write (strxml.tostring ()) Pw.close ()}
Generated XML file
<interview> <data> <person id= ' 05891 ' comments= ' social recruitment ' > <title> & Lt;position code= ' P7 ' >staff se</position> </title> <age>29</age> <assessme NT interviewer= ' Manager1 ' >tech is ok</assessment> <experience> <phase from= ' * ' to= ' now '
>CompanyA</phase> <phase from= ' to= ' >CompanyB</phase> </experience> </person> <person id= ' 05892 ' comments= ' campus recruitment ' > <title> <position code = ' P6 ' >SE</position> </title> <age>25</age> <assessment interviewer= ' Manage R2 ' >tech is ok</assessment> <experience> <phase from= ' * to= ' now ' >universitya</ph
ase> <phase from= ' to= ' >CompanyB</phase> </experience> </person> </data> <interviewinfo> <date>2016-10-12</date> <address>meetingroom 402</address> <organizat or dept= ' cloud ' >ZhangSan</organizator> </interviewInfo> </interview>
Run screenshots