2012-02-15 4 views
0

Possible Duplicate:
How to read XML response from a URL in java?はファイル

私は私のウェブサーバからのXMLファイルを読み込み、ListView上での内容を表示しようとしているとしてリモートXMLを使用するので、私はこのようなファイルを読んでいる:

を私はこの問題を持つとどのようにそれを修正するためだなぜ

java.io.FileNotFoundException: /http:/mydomainname.com/feed.xml (No such file or directory)

File xml = new File("http://example.com/feed.xml"); 
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
Document doc = dBuilder.parse(xml); 
doc.getDocumentElement().normalize(); 

NodeList mainNode = doc.getElementsByTagName("article"); 
// for loop to populate the list... 

問題は、私はこのエラーを取得していますということですか?

+1

ファイルクラスはダウンロードされません。さらに[URI](http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#File%28java.net.URI%29) – bgs

答えて

4

ファイルはローカルファイルを参照するためのものです。

リモートURIを指すようにしたい場合は、最も簡単なあなたは、後に、JavaのストリーミングAPIへの感謝を見ることができるように、簡単にあなたのコードのロジックを適応させることができ、クラスのURL

//modified code 
URL url = new URL("http://example.com/feed.xml"); 
URLConnection urlConnection = url.openConnection(); 
InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 

//your code 
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
Document doc = dBuilder.parse(in); 

を使用することですファイルの内容を処理します。これは、クラスDocumentBuilderの解析メソッドのオーバーロードによるものです。

1

入力ストリームとしてxmlを取得するにはHTTPURLConnectionを使用し、それにDocumentBuilderを渡す必要があります。そこからロジックを使用できます。

DefaultHttpClient client = new DefaultHttpClient(); 
HttpResponse resp = client.execute(yourURL); 

if(resp.getStatusCode == 200) 
{ 
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = factory.newDocumentBuilder(); 
Document doc = builder.parse(resp.getEntity().getContent()); 
} 

注:ここに入力すると、構文エラーが発生することがあります。

0

URLオブジェクトを使用してファイルを読み取る必要があります。たとえば、次のように試してみてください。

URL facultyURL = new URL("http://example.com/feed.xml"); 
InputStream is = facultyURL.openStream(); 
+0

教員を使用する必要があります。あなたは大学ですか? – Snicolas

+0

私が掲載したコードは、年末試験のスケジューリングに役立つ高校向けのアプリケーションからのものです。 – Thorn