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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值