xml解析,hashmap解析二层xml

该博客介绍如何使用Java的DOM4J库解析XML文件,特别是处理包含二层结构的HashMap。通过示例代码展示了从XML文件中读取数据并将其存储到HashMap中的过程。
摘要由CSDN通过智能技术生成

package com;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import jxl.read.biff.BiffException;

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

public class XmlParse {

/**
 * @param args
 * @throws DocumentException 
 * @throws IOException 
 * @throws BiffException 
 */
    // TODO Auto-generated method stub  
private Map<String,String> stateMap=new HashMap<String,String>();
private Map<String,Map> cityMap=new HashMap<String,Map>();

public XmlParse(String citypath ) throws DocumentException, BiffException, IOException{
    this.cityparse(citypath);
}

 public void cityparse(String citypath) throws DocumentException{
    File inputXml=new File(citypath);
    SAXReader saxReader=new SAXReader();        
    Document document=saxReader.read(inputXml);
    Element location=document.getRootElement();  
    for(Iterator<?> i=location.elementIterator();i.hasNext();){
        Element country=(Element)i.next();
        for(Iterator<?> j=country.elementIterator();j.hasNext();){
            try {
                Element state=(Element)j.next();
                String statename=state.attributeValue("Name");
                String statecode=state.attributeValue("Code");
                stateMap.put(statename,statecode );                 
                Map<String,String> tmpCity=new HashMap<String,String>();
                for(Iterator<?> h=state.elementIterator();h.hasNext();){
                     try{
                          Element city=(Element)h.next();
                          String cityname=city.attributeValue("Name");
                          String citycode=city.attributeValue("Code");
                          tmpCity.put(cityname,citycode );
                         }catch(Exception  e){ 
                           System.out.println(e.getMessage());
                         }                 
                    cityMap.put(statename, tmpCity);
                   }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println(e.getMessage());
            }
            }
            break;          
 }
   // System.out.println(citypath+"解析完成,总共有"+num+"个city");     

}

 public String queryState(String stateName){
     return stateMap.get(stateName);
 }
 public String queryCity(String stateName ,String cityName){
    Map<String,String> tmp=cityMap.get(stateName);
    return tmp.get(cityName);//返回城市代码
 }   

}

xml部分定义为:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值