package com.bluedon.track.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @Title: ParseXmlUtil.java
* @Package com.bluedon.track.util
* @Description: 解析xml文件工具类
* @author ssdu
* @date 2017年7月31日 下午3:04:24
* @version V1.0
*/
public class ParseXmlUtil {
/**
* @Title: parseXml
* @Description: 解析xml
* @param
* @return List<Map<String,Object>>
* @throws IOException
*/
public static List<Map<String, Object>> parseXml(File file,String[] arr,String rootPath) throws IOException {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Document doc;
doc = Jsoup.parse(file, "UTF-8");
Elements eles=doc.getElementsByTag(rootPath);
if(null!=eles&&eles.size()>0){
for(Element el:eles){
Map<String, Object> map = new HashMap<String, Object>();
for(String str:arr){
Elements e1=el.getElementsByTag(str);
if(null!=e1&&e1.size()>0){
map.put(str, e1.get(0).text());
}else{
map.put(str, "");
}
}
list.add(map);
}
}
return list;
}
public static JSONObject checkXml(File file){
JSONObject json=new JSONObject();
json.put("msg", "error");
String fileSuffix = ".xml"; /*读取后缀为xml的文件*/
SAXReader reader = new SAXReader();
if(file.getName().lastIndexOf(fileSuffix)!=-1){
try {
reader.read(file);
json.put("msg", "success");
} catch (DocumentException e) {
json.put("reason", file.getAbsolutePath()+":"+e.getMessage());
e.getMessage();
}
}else{
json.put("reason", file.getAbsolutePath()+":不是xml格式文件");
}
return json;
}
}
解析xml文件
最新推荐文章于 2024-05-22 14:29:31 发布