0

I'm converting a JSON to XML String with a java script function. I'm able to even successfully do it. But when I tried to view it in 3 different methods, I get different outputs in .innerHTML when comapred to alert and console.log() What is the reason for such differences? Is there anything wrong that I'm doing.

Here goes my code:

HTML :

<div id="show"></div>

CSS :

#show{
  width:100%; 
  height:200px;
  background:#000;
  color:#fff;
}

JS

function objectToXml(obj) {
        var xml = '';
        for (var prop in obj) {
            if (!obj.hasOwnProperty(prop)) {
                continue;
            }
            if (obj[prop] == undefined)
                continue;
            xml += "<" + prop + ">";
            if (typeof obj[prop] == "object")
                xml += objectToXml(new Object(obj[prop]));
            else
                xml += obj[prop];
            xml += "</" + prop + ">";
        }
        return xml;
    } 
    var myJson={"id":1,"name":"Albert","dob":"2011-02-19","gender":"male","email":"albert@rediffmail.com","language":"English"}
    var xmlString = objectToXml(myJson);
    document.getElementById("show").innerHTML=xmlString;
    alert(xmlString);
    console.log(xmlString);

I don't really understand the reason why XML string is not printed when .innerHTML is used.

Here is a JS FIDDLE

Venky
  • 350
  • 3
  • 15

1 Answers1

1

innerHTML will render the html.

Use innerText instead.

See update fiddle: jsfiddle-link

Ankit Badiya
  • 451
  • 1
  • 4
  • 17
GôTô
  • 7,974
  • 3
  • 32
  • 43
  • Yes! I got the difference. So, when rendering as HTML, basically it eliminates the opening and closing tags just like any other HTML tags. Thanx for the response. – Venky Feb 23 '17 at 10:04
  • 1
    Yes because basically you can use custom tags, see http://stackoverflow.com/questions/2802687/is-there-a-way-to-create-your-own-html-tag-in-html5 – GôTô Feb 23 '17 at 10:09