Use a Remote XML as File [duplicate]

2020-05-01 08:24发布

问题:

This question already has answers here:
Closed 8 years ago.

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