JAVA XML文件转MAP

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiangwudidebaba/article/details/84561604

主要解析的工具包为dom4j这个包

package com.wds.site.test.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


/**
 * @author 作者:jcl
 * @createDate 创建时间:2018年11月27日 上午9:07:49
 */
public class XmlToMap {
	
	public static Map<String,String> xmlFileToMap(String filePath) throws DocumentException{
		
		File file = new File(filePath);
		
		SAXReader reader = new SAXReader();
		
		Document document = reader.read(file);
		
		// 如果是字符串就是用
		//String xmlStr ="XML内容";
		//Document resultDoc = DocumentHelper.parseText(xmlStr);
		
		// 获取根节点
		Element rootEle = document.getRootElement();
		
		System.out.println(rootEle.getName());
		
		// 获取节点下节点的方法
		Element basicEle = rootEle.element("basicData");
		
		// 获取节点节点的值
		String unitName = basicEle.selectSingleNode("unitName").getText();
		
		// 获取节点下的集合信息
		List<Element> listEle = basicEle.elements();
		
		Map<String,String> data = new HashMap<String,String>();
		// 通过遍历将xml节点上的数据放到map里面
		for(int i =0;i<listEle.size();i++){
			
				System.out.println(listEle.get(i).getName());
				
				System.out.println("内容为:"+basicEle.selectSingleNode(listEle.get(i).getName()).getText());
				data.put(listEle.get(i).getName(), basicEle.selectSingleNode(listEle.get(i).getName()).getText());
		}
		
		System.out.println(data.toString());
		
		System.out.println(unitName);
		
		return data;
	}
	
	
	
	public static void main(String[] args) {
		
		String path = "C:\\Users\\wonders_jiangchaoli\\Desktop\\信用平台项目\\测试数据\\年度评分管理.xml";
		
		try {
			Map<String, String> mmp = xmlFileToMap(path);
			
			
			System.out.println(mmp);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

解析的xml文件:

<?xml version="1.0" encoding="UTF-8"?>

-<root type="ndpfglRequest" source="EAM" date="2018-11-26">


-<basicData>

<evaUnitName>test</evaUnitName>

<scoreDate>2018-11-26</scoreDate>

<unitOrgCode>addddd</unitOrgCode>

<unitName>PPPP</unitName>

<score>111.1</score>

</basicData>

</root>

猜你喜欢

转载自blog.csdn.net/jiangwudidebaba/article/details/84561604
今日推荐