[英]How to create one XML file for each record from a database using MarkupBuilder?
I'm pretty new to Groovy so here's my first challenge :-) 我对Groovy来说还很陌生,所以这是我的第一个挑战:-)
I need to create XML files from the result of DB query. 我需要根据数据库查询的结果创建XML文件。
I can create one XML file containing all records from a DB Table: 我可以创建一个XML文件,其中包含来自数据库表的所有记录:
FILE.XML FILE.XML
<?xml version="1.0" encoding="UTF-8"?>
<items>
<Part>12345</Part>
</items>
<items>
<Part>67890</Part>
</items>
But what I need is to create one file per record rather than one file containing all records: 但是我需要的是为每条记录创建一个文件,而不是一个包含所有记录的文件:
FILE1.XML FILE1.XML
<?xml version="1.0" encoding="UTF-8"?>
<items>
<Part>12345</Part>
</items>
FILE2.XML FILE2.XML
<?xml version="1.0" encoding="UTF-8"?>
<items>
<Part>67890</Part>
</items>
Does anyone know if there's a simple way of creating multiple XML files using groovy's MarkupBuilder? 有谁知道使用groovy的MarkupBuilder创建多个XML文件的简单方法吗?
You could do something like this... 你可以做这样的事情...
class Part {
String partNumber
}
def parts = // get a List of Part objects
parts.eachWithIndex { Part p, int idx ->
new File("FILE${idx + 1}.xml").withWriter { writer ->
def builder = new groovy.xml.MarkupBuilder(writer)
builder.items {
part(p.partNumber)
}
}
}
That will create files like FILE1.xml and FILE2.xml that look something like this: 这将创建类似于FILE1.xml和FILE2.xml的文件,如下所示:
<items>
<part>12345</part>
</items>
I hope that helps. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.