xml解析,hashmap解析二层xml

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 stateMap=new HashMap();
private Map cityMap=new HashMap();

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 tmpCity=new HashMap();
                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 tmp=cityMap.get(stateName);
    return tmp.get(cityName);//返回城市代码
 }   

}

xml部分定义为:

你可能感兴趣的:(java语言)