3

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).

1 Answer 1

5

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/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.