Outputting XMLSerializer().serializeToString String to User Savable Text Window

纵然是瞬间 提交于 2019-12-13 05:15:47

问题


I am currently using the following code to display the XML code from part of the DOM.

var sXML = new XMLSerializer().serializeToString(document.getElementsByTagName("TopElementOfBlockOfInterest")[0]);
var win;
var doc;
win = window.open("", "", "",false);
doc = win.document;
doc.open("text/plain");
doc.write(sXML);
doc.close();

What I see is XML code. However, when I choose "Save As" on Firefox 20.0, what is saved is an html file. Is there a way to display the XML string in a form in which the user save save the XML code to a file? The way it is now, the user can copy and paste but I would prefer a more conventional Save operation.


回答1:


Convert it to a data uri and then open that

var uri = new XMLSerializer().serializeToString( // serialise
        document.getElementsByTagName("TopElementOfBlockOfInterest")[0]
    ),
    win;
uri = 'data:text/plain,' + window.encodeURIComponent(uri); // to data URI
win = window.open(uri, '_blank'); // open new window

SaveAs will now default to .txt. You may also wish to use MIME text/xml or application/xml as you're actually displaying XML content, however this might be rendered rather than displayed as plain text, when viewed in a browser.



来源:https://stackoverflow.com/questions/16238701/outputting-xmlserializer-serializetostring-string-to-user-savable-text-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!