簡體   English   中英

將HTML內容保存在本地存儲中

[英]Save content of HTML in local storage

我想從鏈接中獲取xml文件,例如

http://api.worldbank.org/countries/GBR/indicators/NY.GDP.MKTP.KD.ZG?date=2004:2012

它返回一個xml文件,我不知道如何使用java或javascripts將該文件保存在名為“ temp”的文件夾中,實際上,我不想向用戶顯示該鏈接的結果,動態鏈接。

請幫忙!!!

我建議您在這種情況下使用像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.

謝謝!

好吧,您的身體是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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM