前言
最近在项目中遇到了需要解析xml,网上找了一圈也没有对应的解析模板,没办法自己手动搞了一个出来,类似的都可以使用,希望尽量可以帮到大家
一、主方法入口
这里省略controller层直接进来,读取端上传的文件,添加非空判断。inputStream流通过自定义工具类的转换方法转成file文件,再将其转为ZipFile进行循环读取。
/**
* 读取传入的xml
*/
public Result readXml(MultipartFile multipartFile) throws Exception {
// 判断是否有文件
if (multipartFile == null || multipartFile.isEmpty()) {
return Result.failed("请选择要导入的文件");
}
File zipFile = new File(multipartFile.getOriginalFilename());
// 将zip文件夹中文件通过inputStream形式存入zipFile
FileUtil.inputStreamToFile(multipartFile.getInputStream(), zipFile);
HashMap<String, JSONObject> map = readZipFile(zipFile);
zipFile.delete();
return Result.success(readXmlRespVO);
}
二、自定义工具类
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author yhl
* @date 2023/7/19 17:49
*/
@Slf4j
public class FileUtil {
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.flush();
os.close();
ins.close();
} catch (Exception e) {
log.error(" FileUtil下 --> inputStreamToFile() 异常 {}",e);
}
}
}
三、主体解析方法
public HashMap<String, JSONObject> readZipFile(File file) throws Exception {
ZipFile zip = new ZipFile(file, Charset.forName("GBK"));
InputStream in = new BufferedInputStream(new FileInputStream(file));
ZipInputStream zis = new ZipInputStream(in);
HashMap<String, JSONObject> map = new HashMap<>();
// 循环zip包下的文件,只读取后缀是xml格式的
for (Enumeration enumeration = zip.entries(); enumeration.hasMoreElements(); ) {
ZipEntry ze = (ZipEntry) enumeration.nextElement();
if (ze.getName().endsWith(".xml") && ze.getSize() > 0) {
log.info("file - " + ze.getName() + " : " + ze.getSize() + " bytes");
BufferedReader br = new BufferedReader(new InputStreamReader(zip.getInputStream(ze), StandardCharsets.UTF_8));
// 解析读取xml
StringBuffer reqXmlData = new StringBuffer();
String s;
while ((s = br.readLine()) != null) {
reqXmlData.append(s);
}
br.close();
JSONObject jsonObject = XML.toJSONObject(reqXmlData.toString());
map.put(ze.getName(), jsonObject);
log.info("JSONObject {}", JacksonUtil.toJsonString(jsonObject));
}
}
zis.closeEntry();
zis.close();
zip.close();
return map;
}
我这里使用map进行返回,是由于业务需求更加方便,小伙伴们以其他方式返回都是可以的。
总结
以上就是今天要讲的内容了,简单的整合了一个读取zip包中xml文件的方法。