[J2SE] 請問從url讀取xml的方法
大家好 小弟目前是Java超新手 因為工作上需要從url取得xml
該url是google map api
https://maps.googleapis.com/maps/api/distancematrix/xml?
origins=xxxx&destinations=yyyy&language=zh_TW&sensor=false
透過http get這個url Google就會return一個xml
顯示xxxx到yyyy的距離
目前透過 //getURL是要取得的網址
URL getUrl = new URL(getURL);
HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
已經可以把那個xml print出來
但我只需要該xml中的某一個tag的value 也就是distance這個tag
Google找到了DOM, JDOM, DOMj4, SAX等相關方法
可是大多都是從file中讀取xml 不曉得要怎麼從http get去讀@@
嘗試了
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new InputStreamReader(connection.getInputStream(),"utf-8"));
Element root = document.getRootElement();
List<Element> list = root.getChildren("distance");
for(int i=0; i<list.size(); i++){
Element element = (Element) list.get(i);
String distance = element.getChildText("distance");
System.out.println(distance);
}
或是
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(connection.getInputStream(),"utf-8");
Element root = document.getDocumentElement();
code沒有報錯 但運行都拋出了例外 但不知道錯在哪@@
偏偏api doc都看不太懂 因為沒有範例T.T
還請各位大大提點 感謝
不好意思 新手上路 還請見諒 以下是error msg
Exception in thread "main" java.lang.Error: 尚未解決的編譯問題:
未處理的異常狀況類型 ParserConfigurationException
未處理的異常狀況類型 SAXException
at googleMap.test.main(test.java:11)
大致上用哪一種方法都是會拋出該方法的exception
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 122.116.194.91
推
10/01 10:12, , 1F
10/01 10:12, 1F
Ps大 因為這個部分之後可能會大量的access
怕存檔又讀檔會影響performance, 所以也傾向用SAX多於DOM, 但不會用T.T
→
10/01 10:21, , 2F
10/01 10:21, 2F
S大 剛也稍微看了一下json, 可是因為整個平台目前都是以xml在交換資料
所以說xml勢必也得趕快熟悉才行~
※ 編輯: PTTCEO 來自: 122.116.194.91 (10/01 10:25)
※ 編輯: PTTCEO 來自: 122.116.194.91 (10/01 10:28)
→
10/02 18:26, , 3F
10/02 18:26, 3F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 3 篇):
java 近期熱門文章
PTT數位生活區 即時熱門文章