George
George

Reputation: 2110

Output XML code with Jquery

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

Answers (1)

Nicola Peluchetti
Nicola Peluchetti

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

Related Questions