Use a Remote XML as File [duplicate]

◇◆丶佛笑我妖孽 提交于 2019-12-31 05:18:07

问题


Possible Duplicate:
How to read XML response from a URL in java?

I'm trying to read an XML file from my web server and display the contents of it on a ListView, so I'm reading the file like this:

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...

The problem is that I'm getting this error:

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

Why I'm having this problem and how to correct it?


回答1:


File is meant to point to local files.

If you want to point to a remote URI, the easiest is to use the class 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 );

As you can see, later on, thanks to java streaming apis, you can easily adapt your code logic to work with the content of the file. This is due to an overload of the parse method in class DocumentBuilder.




回答2:


You need to use HTTPURLConnection to get xml as input stream and pass it DocumentBuilder, from there you can use the logic you have.

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());
}

Note: I just type here, there may be syntax errors.




回答3:


You need to read the file using a URL object. For instance, try something like this:

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


来源:https://stackoverflow.com/questions/9302476/use-a-remote-xml-as-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!