读取XML文件 Java

本示例主要功能是读取XML文件的表名,和字段信息,使用MyBatis进行对数据库的读写操作。

/*加载xml文件的类,采用dom4j的方式*/
public class ConfUtil {

	private static Log log = LogFactory.getLog(ConfUtil.class);
	private static final String confFile = ConfUtil.class.getClassLoader()
			.getResource("conf/zdry.xml").toString().substring(5);
	/*Map<String, List<String>中Key为表名,value为字段名,因为Map中Key不能重复,所以需将字段名加到list中,取出后再进行处理*/
	public static Map<String, List<String>> getConfigMap() {
		Map<String, List<String>> column = new HashMap<String, List<String>>();
		Map<String, String> map = new HashMap<String,String>();
		try {
			//载入xml文件
			SAXReader saxReader = new SAXReader();
			saxReader.setIgnoreComments(true);
			Document document = saxReader.read(new File(confFile));
			//遍历table节点
			Iterator<Element> itTable = document.getRootElement().elementIterator("table");
			while(itTable.hasNext()){
				Element eleTable = itTable.next();
				String tabName = eleTable.attributeValue("name");
				// 遍历column节点。
				Iterator<Element> itColumn = eleTable.elementIterator("column");
				ArrayList<String> al = new ArrayList<String>();
				while (itColumn.hasNext()) {
					Element eleQualifier = itColumn.next();
					String quaName = eleQualifier.elementTextTrim("name");                                    //将字段加到list
					al.add(quaName);
				}
				column.put(tabName, al);//添加Map
				
			}

			
		} catch (Exception e) {
			log.info("没找到zdry.xml 文件!");
		}
		
		return column;
	}

 所要读取的XML文件为ZDRY.xml

<?xml version="1.0" encoding="UTF-8"?>
<tables>
	<table name="V_LC_WA_DS_ICP" updatetime="UpdateTime" description="互联网信息">
		<!-- 地址 -->
		<column>
			<name>Address</name>
		</column>
		<column>
			<name>DomainName</name>
		</column>
		<column>
			<name>Tel</name>
		</column>	
		<column>
			<name>Sex</name>
		</column>
		<column>
			<name>no</name>
		</column>
		<column>
			<name>Sex</name>
		</column>
	</table>
	<table name="sdfsd" updatetime="UpdateTime" description="互联网信息">
		<!-- 地址 -->
		<column>
			<name>1</name>
		</column>
		<column>
			<name>2</name>
		</column>
		<column>
			<name>3</name>
		</column>	
		<column>
			<name>4</name>
		</column>
		<column>
			<name>5</name>
		</column>
		<column>
			<name>6</name>
		</column>
	</table>
</tables>

 调用getConfigMap( ),将返回的Map进行处理,对每一个Key和value添加到一个Map中,要插入的表名只有6个字段

public void doZdryJob(String start,String end){
		Map<String, List<String>> ma = ConfUtil.getConfigMap();
		Set set = ma.keySet();//获取Map中所有的Key
		Iterator iter = set.iterator();
		
		while (iter.hasNext()) {//是否存在下一个元素
		Map<String, String> map = new HashMap<String,String>();
		ma.clear();
		String key = (String) iter.next();
		map.put("tableName", key);
		map.put("column1", ma.get(key).get(0));
		map.put("column2", ma.get(key).get(1));
		map.put("column3", ma.get(key).get(2));
		map.put("column4", ma.get(key).get(3));
		map.put("column5", ma.get(key).get(4));
		map.put("column6", ma.get(key).get(5));
		service.updateZdry(map);
		}
	}

 

你可能感兴趣的:(读取XML文件 Java)