简体   繁体   中英

How to force download xml file in javascript?

Given this solution on how to create XML format to my data ( Convert JavaScript object (array) to XML )

I need now a way to make auto download this into a.xml file this is my code:

toXml = (data) => {
    return data.reduce((result, el) => {
        if (el.title && el.author)
            return result + `<BookData><title>${el.title}</title><author>${el.author}</author></BookData>\n`
        if (el.title && !el.author)
            return result + `<BookData><title>${el.title}</title></BookData>\n`
        if (!el.title && el.author)
            return result + `<BookData><author>${el.author}</author></BookData>\n`
    }, '')
}

if (type == 2)
{
    let data = this.toXml(arrayData);
    console.log(data);
}

Where I pass the data to create my XML?

What should I code instead of console.log(data); so I can get the downloaded.xml file?

Edit: Answered in How to create and download an XML file on the fly using javascript?

Better late than never. This code downloads an XML file using javascript:

 var pseudoelement = document.createElement("a");

  var filename = "example.xml";
  var pseudoelement = document.createElement("a");
  var blob = new Blob([toXml ], { type: "text/plain" });

  pseudoelement.setAttribute("href", window.URL.createObjectURL(blob));
  pseudoelement.setAttribute("download", filename);

  pseudoelement.dataset.downloadurl = ["text/plain", pseudoelement.download, pseudoelement.href].join(":");
  pseudoelement.draggable = true;
  pseudoelement.classList.add("dragout");

  pseudoelement.click();

thank_for_this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM