views:

305

answers:

4

Hi,

I've have some javascript code that transforms XML with XSLT. I now want the user to be able to save that new XML (either by prompting them or throwing the new XML up as a file or something so that the user can then save it. Anybody know how to do that?

var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
xmldoc.async = false;
xmldoc.loadXML(responseText); // responseText is xml returned from ajax call
//apply the xslt
var xsldoc = new ActiveXObject("Microsoft.XMLDOM");
xsldoc.async = false;
xsldoc.load("../xslt/ExtraWorkRequest.xslt");
var content = xmldoc.transformNode(xsldoc);

// HOW DO I GET THE USER TO SAVE THE XML (content) AS A FILE????

Any ideas?

Thanx,

dman

+1  A: 

By default, you can't. Browser isn't supposed to access your local disks for security reasons.

But, if you can ask your user to change it's security settings (and you should not to ask), you can to use FileSystemObject or even your Microsoft.XMLDOM.Save method.

Rubens Farias
+1  A: 

You cannot do it with 100% client-side JavaScript with the default security settings. You'll need to implement some server-side logic. In your case, you'll be able to do the XML transformation server-side, as well.

http://www.bigresource.com/Tracker/Track-javascripts-ijfTJlI9/

http://support.microsoft.com/kb/q260519/

Jason Kealey
+1  A: 

You could construct a data: URI with a media type of application/octet-stream.

function download (data, charset) {
  if (!charset) {
    charset = document.characterSet;
  }
  location.href = ["data:application/octet-stream;charset=",
                   charset, ",", encodeURIComponent(data)
                  ].join("");
}

All browsers except IE support data: URIs. I think IE8 may support them, but only for images. For IE, a workaround could be to send the data to a server (including document.characterSet) and then load a page that has something like the following header:

Content-Type: application/xml; charset={document.characterSet}
Content-Disposition: attachment

If you want to give the file a name too, use Content-Disposition: attachment; filename=....

Also, for any of this to work, you have to convert your XML to a string first.

Eli Grey
A: 

I do this with code snippets on my blog (user can click on the save button, and the snippet will come up in their default text editor, where they can tweak it and/or copy it into their app).

It works by putting all the textual data inside of a hidden field, and then submits it to a very simple server-side HTTP handler. The handler just grabs the hidden field value and spits it right back out in the response with the right content-disposition header, giving the user the open/save download prompt.

This is the only way I could get it to work.

Josh Stodola