Reputation: 2110
Consider the following script for outputting some XML code:
var xmlAsString = '<?xml version="1.0"?><person><name gender="male"></name></person>';
$(document).ready(function(){
$(".generator").click(function(){
alert(xmlAsString);
$("#container").append("<div id='contXML'>"+xmlAsString+"</div>")
});
});
The alert outputs everything as I want but nothing shows later. If I put some random string variable (without the < > chars everything works fine).
Upvotes: 3
Views: 3123
Reputation: 76870
That's because you have to html encode your xml otherwise the browser tries to parse it. I use this simple function.
var xmlAsString = '<?xml version="1.0"?><person><name gender="male"></name></person>';
function htmlEncode(value){
return $('<div/>').text(value).html();
}
$(document).ready(function() {
$(".generator").click(function() {
alert(xmlAsString);
$("#container").append("<div id='contXML'>" + htmlEncode(xmlAsString) + "</div>")
});
});
Fiddle here http://jsfiddle.net/DqDEU/
Upvotes: 5