日期:2014-05-20  浏览次数:20785 次

dom4j 读取xml文件

public class xml2Instance {
public static void main(String[] args){
SAXReader reader = new SAXReader();

try {
Document doc =  reader.read
(new FileInputStream("C:/Users/Administrator/Desktop/first.xml"));
Element root = doc.getRootElement();
Customer customer = new Customer();
System.out.println(root.attributeValue("CustName"));
customer.setCustName(root.attributeValue("CustName"));
customer.setType(root.attributeValue("Type"));
customer.setDest(root.attributeValue("Dest"));
customer.setFlight(root.attributeValue("Flight"));
customer.setTime(root.attributeValue("Time"));

System.out.println(customer);


}
}


各位大侠,为什么我读不到文件的值呢,这个first.xml我是刚用dom4j写的,却是存在啊
里面也显示内容,为嘛在读取的时候会显示null呢
?

------解决方案--------------------
不知道你xml文件是什么样的,只是感觉你外层应该没有获取Customer(); 对象
给你一个例子吧

public Map<String, String> getProvinceMap() {
Map<String, String> proMap = new HashMap<String, String>();
try {
InputStream in = DBHelper.getDBHelper().getContext().getResources()
.getAssets().open("province.xml");
InputStream is = IOHelper.fromInputStreamToInputStreamInCharset(in,"utf-8");
SAXReader sr = new SAXReader();// 获取读取xml的对象。
Document document = sr.read(is);
Element root = document.getRootElement();
List<?> elementlist = root.elements("city");
for (Object obj : elementlist) {
Element row = (Element) obj;
String quName = row.attribute("quName").getText();
String pyName = row.attribute("pyName").getText();
proMap.put(quName, pyName);
}
} catch (Exception e) {
Log.e("tag", "read configure error");
}
return proMap;
}



<?xml version="1.0" encoding="utf-8"?>
<china dn="day">
<city quName="黑龙江" pyName="heilongjiang" cityname="哈尔滨" state1="21" state2="7" stateDetailed="小到中雨转小雨" tem1="21" tem2="13" windState="东风4-5级转3-4级"/>
<city quName="吉林" pyName="jilin" cityname="长春" state1="8" state2="9" stateDetailed="中雨转大雨" tem1="19" tem2="14" windState="东南风3-4级"/>
<city quName="辽宁" pyName="liaoning" cityname="沈阳" state1="8" state2="9" stateDetailed="中雨转大雨" tem1="21" tem2="18" windState="东南风小于3级转3-4级"/>
</china>