Skip to content

Instantly share code, notes, and snippets.

@epcnt19
Created December 5, 2016 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epcnt19/a7aeb9af23b279411d948673c2d6eb5a to your computer and use it in GitHub Desktop.
Save epcnt19/a7aeb9af23b279411d948673c2d6eb5a to your computer and use it in GitHub Desktop.
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
/*
* 駅データのAPIサイト(http://www.ekidata.jp)からXMLデータを取得し,パースするプログラム.
* このクラスの例では,JR山手線(11302.xml)のデータを取ってきている.
*/
//XMLTestクラス
class XMLTest{
//mainメソッド
public static void main(String argvs[]){
try{
//XMLTestインスタンスを生成し,startメソッドを呼ぶ
new XMLTest().start();
}catch(Exception e){
e.printStackTrace();
}
}
//startメソッド
private void start() throws Exception{
//APIのURL
String xml_url = "http://www.ekidata.jp/api/l/11302.xml";
URL url = new URL(xml_url);
//コネクションを張る
URLConnection connection = url.openConnection();
//パースする
Document doc = parsersXML(connection.getInputStream());
//欲しい要素を指定する
NodeList station_name = doc.getElementsByTagName("station_name");
NodeList lon = doc.getElementsByTagName("lon");
NodeList lat = doc.getElementsByTagName("lat");
//forを回して要素を出力する
for(int i=0;i<station_name.getLength();i++){
System.out.println(station_name.item(i).getTextContent());
System.out.println(lon.item(i).getTextContent());
System.out.println(lat.item(i).getTextContent());
}
}
//parsersXMLメソッド.GETリクエストで取得したXMLデータをパースする
private Document parsersXML(InputStream stream) throws Exception{
DocumentBuilderFactory objDocumentBuilderFactory = null;
DocumentBuilder objDocumentBuilder = null;
Document doc = null;
try{
objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();
doc = objDocumentBuilder.parse(stream);
}catch(Exception e){
e.printStackTrace();
}
return doc;
}
}
@epcnt19
Copy link
Author

epcnt19 commented Dec 5, 2016

//出力例

大崎
139.728439
35.619772
五反田
139.723822
35.625974
目黒
139.715775
35.633923
恵比寿
139.71007
35.646685
渋谷
139.701238
35.658871
原宿
139.702592
35.670646
代々木
139.702042
35.683061
新宿
139.700464
35.689729
新大久保
139.700261
35.700875
高田馬場
139.703715
35.712677
目白
139.706228
35.720476
池袋
139.711086
35.730256
大塚
139.728584
35.731412
巣鴨
139.739303
35.733445
駒込
139.748053
35.736825
田端
139.761229
35.737781
西日暮里
139.766857
35.731954
日暮里
139.771287
35.727908
鶯谷
139.778015
35.721484
上野
139.777043
35.71379
御徒町
139.774727
35.707282
秋葉原
139.773288
35.698619
神田
139.770641
35.691173
東京
139.766103
35.681391
有楽町
139.763806
35.675441
新橋
139.758587
35.666195
浜松町
139.757135
35.655391
田町
139.747575
35.645736
品川
139.738999
35.62876

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment