XML文件节点转化为大写方式

最近项目中需要对xml文件进行解析!有时候会遇到xml的节点大小写不一致的问题,因此写了个方法把xml文件中的节点全部转为大写的方式,在这里做个备忘。代码如下,
	public static Element elementToUpper(Element ele){
		ele.setName(ele.getName().toUpperCase());
		List<Attribute> attrList = ele.getAttributes();
		if(!attrList.isEmpty()){
			for(int i=0, m = attrList.size(); i < m; i++){
				Attribute attr = attrList.get(i);
				attr.setName(attr.getName().toUpperCase());
			}
		}
		List<Element> eleList = ele.getChildren();
		if(!eleList.isEmpty()){
			for(int i=0, m=eleList.size(); i<m; i++){
				Element element = eleList.get(i);
				element.setName(element.getName().toUpperCase());
				elementToUpper(element);
			}
		}
		return ele;
	}


下面这个是把xml文件中的值根据节点名称存放到Map中:
	public static Map<String, String> getElementAll(Element ele){
		Map<String, String> map = new HashMap<String, String>();
		List<Attribute> attrList = ele.getAttributes();
		if(!attrList.isEmpty()){
			for(int i=0, m = attrList.size(); i < m; i++){
				Attribute attr = attrList.get(i);
				map.put(ele.getName().toUpperCase() + attr.getName().toUpperCase(), attr.getValue());
			}
		}
		List<Element> eleList = ele.getChildren();
		if(!eleList.isEmpty()){
			for(int i=0, m=eleList.size(); i<m; i++){
				Element element = eleList.get(i);
				Map<String, String> eleMap = getElementAll(element);
				mapPutAll(map, eleMap);
			}
		}else if(null != ele.getValue() && ele.getValue().length() > 0){
			map.put(ele.getName().toUpperCase(), ele.getValue());
		}
		return map;
	}


	/**
	 * 将源Map拷贝到目标Map当中
	 * 如果目标Map存在源Map中的对象,则在原key值上加上一个“_1”,如果还存在则“_2”,
	 * 如:key,key_1,key_2...
	 * @param target
	 * @param source
	 * @return
	 * @author kane xiang
	 */
	private static Map<String, String> mapPutAll(Map<String, String> target, Map<String, String> source){
		int num = 1;
		boolean bool = true;
		Iterator<Entry<String, String>> it = source.entrySet().iterator();
		while(it.hasNext()){
			bool = true;
			Entry<String, String> entry = it.next();
			if(null == target.get(entry.getKey())){
				target.put(entry.getKey(), entry.getValue());
			}else{
				while(bool){
					String key = entry.getKey() + "_" + num;
					if(null == target.get(key)){
						target.put(key, entry.getValue());
						bool = false;
					}else{
						num ++;
					}
				}
			}
		}
		return target;
	}

你可能感兴趣的:(xml)