/**
* 创建xml文件
* @param dirName 文件夹名称
* @param rootName 根节点
* @param channelName 子节点
* @param fileName 文件名
* @param filePath 文件路径
* @param mapItems 结果集
* @Param fileSize 文件大小 (子节点个数)
*/
public static void createXml(String dirName,String rootName, String channelName, String fileName, String filePath, List<Map<String, String>> mapItems,Integer fileSize) {
if (mapItems == null) {
return;
}
List<List<Map<String,String>>> trans = listChunk(mapItems,fileSize);
try {
int token = 0;
for (int i = 0; i < trans.size(); i ++) {
// 生成一个根节点
Element root = new Element(rootName);
// 生成一个document对象
Document document = new Document(root);
//添加子节点数据
buildNodes(root, channelName, trans.get(i) );
Format format = Format.getCompactFormat();
// 设置换行Tab或空格
format.setIndent(" ");
format.setEncoding("UTF-8");
// 创建XMLOutputter的对象
XMLOutputter outputer = new XMLOutputter(format);
// 利用outputer将document转换成xml文档
File file = null;
if(trans.size() <= 1){
file = new File(filePath +File.separator+dirName, fileName + ".xml");
}else {
file = new File(filePath +File.separator+dirName, fileName +"_"+ token + ".xml");
}
if (!file.exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
outputer.output(document, fos);
fos.close();
token++;
root.detach();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void buildNodes(Element root, String channelName, List<Map<String, String>> mapItems) {
Element channel = null;
Element node = null;
Long i = 0L;
for (Map<String, String> mapItem : mapItems) {
if ("".equals(channelName)) {
channel = new Element("item" + i);
i++;
} else {
channel = new Element(channelName);
}
for (Map.Entry<String, String> entry : mapItem.entrySet()) {
node = new Element(entry.getKey());
if (!(entry.getValue() instanceof String)) {
String text = String.valueOf(entry.getValue());
node.setText(text);
} else {
node.setText(entry.getValue());
}
channel.addContent(node);
}
root.addContent(channel);
}
}
public static List<List<Map<String,String>>> listChunk(List<Map<String,String>> chunkList, int chunkNum) {
if (chunkList == null || chunkNum <= 0) {
List<List<Map<String,String>>> t = new ArrayList<>();
t.add(chunkList);
return t;
}
Iterator<Map<String,String>> iterator = chunkList.iterator();
int i = 1;
List<List<Map<String,String>>> total = new ArrayList<>();
List<Map<String,String>> tem = new ArrayList<>();
while (iterator.hasNext()) {
Map<String,String> next = iterator.next();
tem.add(next);
if (i == chunkNum) {
total.add(tem);
tem = new ArrayList<>();
i = 0;
}
i++;
}
if(!CollectionUtils.isEmpty(tem)){
total.add(tem);
}
return total;
}
工具类-创建xml格式文件
最新推荐文章于 2022-11-21 15:12:59 发布