1

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?

Pingolin
  • 3,161
  • 6
  • 25
  • 40
Hernan Alonso
  • 11
  • 1
  • 4
  • 1
    You could use something like [Blob API](https://developer.mozilla.org/en-US/docs/Web/API/Blob) in JavaScript in order to create a client-side URL object from that data, and then use any of the [multiple solutions](https://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link) to download the blob. Slightly more inconsistent than what it might be desirable, but it works. – danirod Apr 20 '19 at 16:48

1 Answers1

2

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