我想从链接获取XML文件像保存内容
http://api.worldbank.org/countries/GBR/indicators/NY.GDP.MKTP.KD.ZG?date=2004:2012
它返回一个XML文件,我不知道如何将这个文件保存我的文件夹名为“临时“使用java或javascripts,实际上我不想显示这个链接的结果给用户,我动态地生成这样的链接。
请帮忙!!!
我想从链接获取XML文件像保存内容
http://api.worldbank.org/countries/GBR/indicators/NY.GDP.MKTP.KD.ZG?date=2004:2012
它返回一个XML文件,我不知道如何将这个文件保存我的文件夹名为“临时“使用java或javascripts,实际上我不想显示这个链接的结果给用户,我动态地生成这样的链接。
请帮忙!!!
我建议你在这种情况下使用像jsoup这样的HTML解析器库。请看下面的步骤以获得更好的信誉:
1. Download jsoup core library (jsoup-1.6.1.jar) from http://jsoup.org/download
2. Add the jsoup-1.6.1.jar file to your classpath.
3. Try the below code to save the xml file from the URL.
package com.overflow.stack;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
/**
*
* @author sarath_sivan
*/
public class XmlExtractor {
public static StringBuilder fetchXmlContent(String url) throws IOException {
StringBuilder xmlContent = new StringBuilder();
Document document = Jsoup.connect(url).get();
xmlContent.append(document.body().html());
return xmlContent;
}
public static void saveXmlFile(StringBuilder xmlContent, String saveLocation) throws IOException {
FileWriter fileWriter = new FileWriter(saveLocation);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(xmlContent.toString());
bufferedWriter.close();
System.out.println("Downloading completed successfully..!");
}
public static void downloadXml() throws IOException {
String url = "http://api.worldbank.org/countries/GBR/indicators/NY.GDP.MKTP.KD.ZG?date=2004:2012";
String saveLocation = System.getProperty("java.io.tmpdir")+"sarath.xml";
XmlExtractor.saveXmlFile(XmlExtractor.fetchXmlContent(url), saveLocation);
}
public static void main(String[] args) throws IOException {
XmlExtractor.downloadXml();
}
}
4. Once the above code is executed successfully, a file named "sarath.xml" should be there in your temp folder.
谢谢!
谢谢sarath,对于你详细的解决方案 – Sid 2012-03-04 17:12:45
顺便说一下,jsoup有什么用和存储sarath.xml文件的位置,我找不到该文件。 – Sid 2012-03-04 17:29:55
考虑上述代码中的两个语句:Document document = Jsoup.connect(url).get(); xmlContent.append(document.body()。html());在这里,我们使用jsoup连接到URL并从连接的URL下载HTML源代码。由于xml文件位于URL的HTML
中,我们可以使用document.body()。html()从正文中提取XML内容。 – 2012-03-04 17:47:29那么你的身体是XML而不是HTML,只需使用Apache HttpClient检索它,并将读取的InputStream泵入FileOutputStream。有什么问题?您是否想以格式化的形式保存解析的内容?
public String execute() {
try {
String url = "http://api.worldbank.org/countries/GBR/indicators/NY.GDP.MKTP.KD.ZG?date=2004:2012";
String saveLocation = System.getProperty("java.io.tmpdir")+"sarath.xml";
XmlExtractor.saveXmlFile(XmlExtractor.fetchXmlContent(url), saveLocation);
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
}
return SUCCESS;
}
我想要它保存在系统的临时目录中,我希望它保存在服务器中,它将在客户端... – Sid 2012-03-14 08:22:50
你的客户端应用程序是用什么编写的? HTML5还是Java? – Perception 2012-03-03 19:39:12
它已被写入Java(struts2),我试过JavaScript,但问题是,它需要用户干预,我需要用户之间 – Sid 2012-03-03 22:30:53