xml解析,hashmap解析二层xml

来源:互联网 发布:mac应用程序删除 编辑:程序博客网 时间:2024/04/29 09:24

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 0
原创粉丝点击