Convert xml to string with jQuery

Yarin picture Yarin · Jun 28, 2011 · Viewed 96.3k times · Source

I'm loading an xml file with jQuery ajax loader, and need to convert it to a string so that I can save it out again using PHP post variables. What is the best way to do this?

<script type='text/javascript'>

jQuery.ajax({
    type: "GET",
    url: "data.xml",
    dataType: "xml",
    success: parseXML
    });


function parseXML(xml) {

    var xml_string = jQuery(xml).text();  // (This doesn't work- returns tagless, unformatted text) 
    alert(xml_string);

}

</script>

Answer

Yarin picture Yarin · Jun 28, 2011

Here it is:

<script type='text/javascript'>

function xmlToString(xmlData) { 

    var xmlString;
    //IE
    if (window.ActiveXObject){
        xmlString = xmlData.xml;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else{
        xmlString = (new XMLSerializer()).serializeToString(xmlData);
    }
    return xmlString;
}   

</script>

Taken from here