JAVA XML文件转MAP

主要解析的工具包为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 = "地址";
		
		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>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值