dom解析xml实现省市区动态级联是一个项目中的一部分,项目是springMVC实现的,其配置文件这儿就不在说了,现只简单列出一些主要的代码。看懂需要有一定的springMVC基础
配置文件中的省的值
city.area.province=黑龙江,湖南
在action中
private @Value("${city.area.province}") String provinceStr;
model.addAttribute("provinceList", ManagerUtil.getSelectBean(provinceStr));//获取省的下拉列表
//根据省获取市 public void getCityListByProvince(@RequestParam("province") String province, Model model, HttpServletResponse response) { try { province = URLDecoder.decode(province, "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } response.setCharacterEncoding("utf-8"); getListValue("province", "city", province, response); } //根据市获取区县 public void getAreaListByCity(@RequestParam("city") String city, Model model, HttpServletResponse response) { try { city = URLDecoder.decode(city, "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } response.setCharacterEncoding("utf-8"); getListValue("city", "area", city, response); } // private void getListValue(String type, String childType, String value, HttpServletResponse response) { StringBuilder sb = new StringBuilder(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File(UserController.class.getResource("/").toString().substring(6) + "/city-area.xml")); NodeList nodeList = document.getElementsByTagName(type); for(int i=0; i<nodeList.getLength(); i++) { Element e = (Element) nodeList.item(i); String name = e.getAttribute("name"); if(name.equals(value)){ NodeList childList = e.getElementsByTagName(childType) ; for(int j=0; j<childList.getLength(); j++) { sb.append(",").append(((Element) childList.item(j)).getAttribute("name")); } break; } } }catch(SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch(ParserConfigurationException e) { e.printStackTrace(); } try { response.getWriter().write(JsonUtil.toJsonString(ManagerUtil.getSelectBean(sb.substring(1).toString()))); } catch (IOException e) { e.printStackTrace(); } }JsonUtil类的toJsonString方法
public static String toJsonString(Object o) { if(o instanceof Collection) { StringBuffer buf = new StringBuffer(""); Object[] objs = JSONArray.fromObject(o).toArray(); for (int i = 0; i < objs.length; i ++) { if(i!=0) buf.append(","); buf.append(JSONObject.fromObject(objs[i]).toString()); } return "{totalCount:" + objs.length + ",root:[" + buf.toString() + "]}"; } return JSONObject.fromObject(o).toString(); }ManagerUtil类中的getSelectBean方法
public static List<SelectBean> getSelectBean(String str) { List<SelectBean> selectBeanList = new ArrayList<SelectBean>(); if (!StringUtils.isEmpty(str)) { for (String item : str.split(",")) { SelectBean selectBean = new SelectBean(); selectBean.setLabel(item.trim()); selectBean.setValue(item.trim()); selectBeanList.add(selectBean); } } return selectBeanList; }jsp主要部分
<script type="text/javascript">function changeCityList(obj) { var citySelect = $("#uCity"); var areaSelect = $("#uArea"); citySelect.empty(); areaSelect.empty(); citySelect.append("<option value=''>请选择市</option>"); areaSelect.append("<option value=''>请选择区/县</option>"); if($(obj).val() != '') { $.ajax({ type: "POST", url: '....../getCityListByProvince.do?province=' + encodeURIComponent(encodeURIComponent($(obj).val())), async:false, dataType:'text', success: function(json) { var data = (eval('(' + json + ')')).root; for(var i=0; i<data.length; i++){ citySelect.append("<option value=" + data[i].value + ">" + data[i].label + "</option>"); } } }); } } function changeAreaList(obj) { // alert($(obj).val()); var areaSelect = $("#uArea"); areaSelect.empty(); areaSelect.append("<option value=''>请选择区/县</option>"); if($(obj).val() != ''){ $.ajax({ type: "POST", url: '...../getAreaListByCity.do?city=' + encodeURIComponent(encodeURIComponent($(obj).val())), async:false, dataType:'text', success: function(json) { // var areaSelect = $("#uArea"); var data = (eval('(' + json + ')')).root; for(var i=0; i<data.length; i++){ areaSelect.append("<option value=" + data[i].value + ">" + data[i].label + "</option>"); } } }); } } </script> <div class="rfm"> <table> <tr> <th><span class="rq">*</span><label for="369bQT">省:</label></th> <td> <select id="uProvince" onchange="changeCityList(this)" name="uProvince" style="width:230px"> <option value="">请选择省份</option> <c:forEach items="${provinceList }" var="province"> <option value="${province.value }">${province.label }</option> </c:forEach> </select> </td> </tr> </table> </div> <div class="rfm"> <table> <tr> <th><span class="rq">*</span><label for="369bQT">市:</label></th> <td> <select id="uCity" name="uCity" onchange="changeAreaList(this)" style="width:230px"> <option value="">请选择市</option> </select> </td> </tr> </table> </div> <div class="rfm"> <table> <tr> <th><span class="rq">*</span><label for="369bQT">区:</label></th> <td> <select id="uArea" name="uArea" style="width:230px"> <option value="">请选择区/县</option> </select> </td> </tr> </table> </div>
city-area.xml的部分内容(这里主要是说明一下它的格式)
<?xml version="1.0" encoding="UTF-8" ?> <root name="中国"> <province name="黑龙江" id="黑龙江"> <city name="大庆市"> <area name="萨尔图区"/> <area name="龙凤区"/> <area name="让胡路区"/> <area name="红岗区"/> <area name="大同区"/> <area name="肇州县"/> <area name="肇源县"/> <area name="林甸县"/> <area name="杜尔伯特蒙古族自治县"/> </city> <city name="七台河市"> <area name="桃山区"/> <area name="新兴区"/> <area name="茄子河区"/> <area name="勃利县"/> </city> </province> </root>