前端之家收集整理的这篇文章主要介绍了
xml解析片段,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
public class ReadXml {
private Element root = null;
public ReadXml() throws FileNotFoundException,JDOMException,IOException {
super();
SAXBuilder sb = new SAXBuilder();//解析器对象
Document doc = sb.build(this.getClass().getResourceAsStream("/city.xml"));//绑定文件
root = doc.getRootElement();//获取根元素
}
public List getProvince(){ //获取省份
ArrayList provinceList = new ArrayList();
List tempList = root.getChildren();//获取所有省份节点
for(int i=0; i
Element province=(Element)tempList.get(i);//子节点转型
provinceList.add(province.getAttributeValue("name"));//获取省份节点属性内容
}
return provinceList;
}
public List getCity(String province){
ArrayList cityList = new ArrayList();
List provincetemplist = root.getChildren();//省份集合
for(int i=0; i
Element provinceElement = (Element)provincetemplist.get(i);
if((provinceElement.getAttributeValue("name")).equals(province)){//如果属性为传进来的名称
List cityTempList = provinceElement.getChildren();//获取子节点集合
for(int j=0; j//循环
Element cityElement = (Element)cityTempList.get(j);//当前城市节点
cityList.add(cityElement.getTextTrim());//增加城市到集合
}
}
}
return cityList;
}
}