user306708
user306708

Reputation: 941

howto display an XMLDocument object with javascript?

My problem is the following: In my javascript, I load an XML document from a server.

var xmlDom =  document.implementation.createDocument("","",null);
xmlDom.async=false;
xmlDom.load("init.xml");

The user can then modify this XML Document by editing various form elements of the displayed webpage. When finished, I'd like to open a new browser tab and display the modified xml in there, so that the user can save it. The question is how to do this without sending the xmlDocument to the server and back. My current hack displays nothing on the page but at least shows the xml in the page source.

    xmlWindow = window.open("");
    xmlWindow.document.open("text/xml");
    xmlWindow.document.write(serializer.serializeToString(xmlDom));
    xmlWindow.document.close();
    xmlWindow.focus();

Someone any idea how to do this properly?

Upvotes: 0

Views: 3903

Answers (2)

user306708
user306708

Reputation: 941

Finally found a way to get what I want (at least for non-ie browsers). What I use is a so called DataUri which makes it possible to present the XML Document as a link. Clicking on the link causes the browser to process the data just as if I would load it from a server. E.g., xsl-stylesheets are processed. here is the (jQuery) code I'm using:

$('#xmllink').attr('href','data:text/xml,' + xml2Str(xmlDom).replace(/"/gi, "'"));

the function xml2str serializes the xml Document to string.

Upvotes: 1

justkt
justkt

Reputation: 14776

You'll need to HTML encode your XML for it to display. Use < for <, > for >, etc. Surround with the pre tag or put it as the data in document.createTextNode(data).

You can also create a text area in your document in your new window and put the XML string in the textarea.

More information in this SO question.

Upvotes: 1

Related Questions