使用远程XML作为文件 [英] Use a Remote XML as File

查看:107
本文介绍了使用远程XML作为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


我想从我的Web服务器读取一个XML文件,并在 ListView 中显示它的内容,这样读取文件:

  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循环来填充列表...

问题在于, m得到这个错误:


java.io.FileNotFoundException:/http:/mydomainname.com/feed.xml(没有这样的文件或目录)


为什么我遇到这个问题以及如何改正它?



如果你想指向一个远程URI,最简单的方法是使用类的url

  //修改后的代码
URL url = new URL(http://example.com /feed.xml);
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());

//你的代码
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(in);

正如您所看到的,稍后,感谢java streaming apis,您可以轻松地调整您的代码逻辑处理文件的内容。这是由于类 DocumentBuilder 中的解析方法的重载。


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?

解决方案

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.

这篇关于使用远程XML作为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆