<?xml version="1.0" encoding="UTF-8"?>
<China>
<province id="01" name="北京">
<city id="0101" name="北京">
<county id="010101" name="北京" weatherCode="101010100"/>
<county id="010102" name="海淀" weatherCode="101010200"/>
<county id="010103" name="朝阳" weatherCode="101010300"/>
<county id="010104" name="顺义" weatherCode="101010400"/>
<county id="010105" name="怀柔" weatherCode="101010500"/>
<county id="010106" name="通州" weatherCode="101010600"/>
<county id="010107" name="昌平" weatherCode="101010700"/>
<county id="010108" name="延庆" weatherCode="101010800"/>
<county id="010109" name="丰台" weatherCode="101010900"/>
<county id="010110" name="石景山" weatherCode="101011000"/>
<county id="010111" name="大兴" weatherCode="101011100"/>
<county id="010112" name="房山" weatherCode="101011200"/>
<county id="010113" name="密云" weatherCode="101011300"/>
<county id="010114" name="门头沟" weatherCode="101011400"/>
<county id="010115" name="平谷" weatherCode="101011500"/>
</city>
</province>
</China>
做了一个天气项目解析城市XML
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ParseXml {
public Map<String,String> read() {
Map<String,String> map = null;
try {
SAXReader reader = new SAXReader();
URL resoucePath = PropertiesLoader.class.getClassLoader()
.getResource("city_code.xml");
File file = new File(resoucePath.getPath());
Document document = reader.read(file);
// 获取根节点
Element root = document.getRootElement();
Iterator<?> iter = root.elementIterator("province"); // 获取根节点下的子节点province
map = new HashMap<String,String>();
// 遍历province节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
Iterator<?> iters = recordEle.elementIterator("city"); // 获取子节点province下的子节点city
// 遍历province节点下的city节点
while (iters.hasNext()) {
Element itemEle = (Element) iters.next();
Iterator<?> itor = itemEle.elementIterator("county"); // 获取子节点city下的子节点county
// 遍历city下的子节点county
while (itor.hasNext()) {
Element countryEle = (Element) itor.next();
String id = countryEle.attributeValue("weatherCode");
String name = countryEle.attributeValue("name");
map.put(id, name);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static void main(String[] args) {
ParseXml parseXml = new ParseXml();
Map<String,String> map = parseXml.read();
for (Entry<String, String> entry: map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+value);
}
}
}
本文详细解析了如何使用Java和DOM4J库从城市XML文件中读取天气信息,涵盖了从顶级节点到子节点的遍历过程,最终将weatherCode与城市名称映射为键值对。
2967

被折叠的 条评论
为什么被折叠?



