解析xml文件

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;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值