Convert XML to String and append to page

rzcl picture rzcl · Mar 28, 2012 · Viewed 95.9k times · Source

I want to convert an xml element like this:

<asin>​B0013FRNKG​</asin>​

to string in javascript

I used XMLSerializer:

new XMLSerializer().serializeToString(xml);

the string only shows on alert() and in the console. On the page it just says

[object Element][object Element]

I want to get the string.

Answer

veblock picture veblock · Mar 28, 2012

You haven't told us how you go about displaying that object. XMLSerializer works on DOM nodes, so your object has to be added somewhere, for example:

document.getElementById('SomeDiv').appendChild(xml); 

and if you just want the full xml string to be displayed:

var xmlText = new XMLSerializer().serializeToString(xml);
var xmlTextNode = document.createTextNode(xmlText);
var parentDiv = document.getElementById('SomeDiv');
parentDiv.appendChild(xmlTextNode);