27

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>
Yarin
  • 173,523
  • 149
  • 402
  • 512
  • What about `jQuery(xml).html()`? Or just `xml`? – Blindy Jun 28 '11 at 13:41
  • Are you looking to extract specific strings from the xml, or simply get the xml string that is returned from the AJAX request? – Ryan Gross Jun 28 '11 at 13:42
  • @Ryan- the former- although I will be saving off the entire xml doc, I need to perform manipulations on it first, so I need to bring it in as xml – Yarin Jun 28 '11 at 13:46
  • 2
    @Blindy- You can't use .html() on xml, and just xml returns = [object Document] – Yarin Jun 28 '11 at 13:49
  • 3
    If you don't need to parse the XML and just get the text, change the dataType to 'text' – Ahmed Nuaman Jun 28 '11 at 14:22
  • Right, so then still load it as 'text', you've then got it as a string. You can then parse the XML by doing $( xmlString ) and bam! – Ahmed Nuaman Jun 29 '11 at 08:01
  • you could always add it to a parent tag, then grab html of the parent tag $('').append(xml).html() – TheJediCowboy Jan 28 '13 at 18:00
  • Note that if the only thing you wanted to do with the XML was display it, then `console.log(xml);` would work better. In Firebug and equivalent, you can then browse the XML document tree instead of having to decipher a complex string (assuming it can become somewhat long.) – Alexis Wilke Jan 30 '16 at 02:43

10 Answers10

61

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

Yarin
  • 173,523
  • 149
  • 402
  • 512
  • 2
    I noticed I got a security error in Firefox when passing a jQuery object to this function, but it seemed to work fine when passing in an XML object. – Justin Ethier May 15 '12 at 21:22
  • `NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument arg 0 [nsIDOMSerializer.serializeToString]` error on firefox, does not work on IE either – SpaceDust__ Oct 26 '12 at 13:17
  • 1
    for those in modern days looking at this solution, the browser test should not be for IE, it should be for the presence of the XMLSerializer, since newer IE has this, but not older. – BobbyTables Jul 17 '15 at 08:27
17

this works around the .innerHtml problem.

$('<div>').append(xmlObj).html()
Gojko Adzic
  • 1,241
  • 10
  • 9
  • 3
    This is good, but it kills the casing on the tags. (Particularly noticeable on SOAP requests.) because – Richard Jun 26 '13 at 19:50
  • If you have only lowercase tags in your DOM tree, this one is better than the Serializer approach as the Serializer may modify the tags with its own namespace at will. In my particular case the Serializer approach did not return the correct xml string but the $.html approach did. – Michael Gollmick Jan 17 '14 at 14:04
  • Michael can u please explain the $.html struggling a lot with case sensitive – Laxminarayana Challagonda Mar 27 '14 at 09:32
5

Spent much time for this problem. With IE 9 above functions should work in another way. Because in IE9 xmlData[0].xml doesn't work (IE still likes jokes). And we must use XMLSerializer with IE v9 and higher (?!)

function xmlToString(xmlData) { // this functions waits jQuery XML 

    var xmlString = undefined;

    if (window.ActiveXObject){
        xmlString = xmlData[0].xml;
    }

    if (xmlString === undefined)
    {
        var oSerializer = new XMLSerializer();
        xmlString = oSerializer.serializeToString(xmlData[0]);
    }

    return xmlString;
}

And example of using it with jQuery 1.8.2 (1.6.4 works too).

   $.ajax(
        {
            type: type,
            url: url,
            data: values,
            dataType: 'html', //get response in plain text
            success: function(response) {    

                //transform it to jQuery XML DOM
                var xmlDoc = jQuery.parseXML(response);
                var xml = $(xmlDoc);

                //do some search and so on
                var divtag = xml.find('div[id="content"]');
                var divtxt = xmlToString(divtag);

                //consume it
                alert(divtxt);
                $('#main-content').html(divtxt);

            }
        });
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Michael T
  • 988
  • 9
  • 9
  • good man! this code `var Serializer = new XMLSerializer(); xmlString = oSerializer.serializeToString(xmlData[0]);` parses XML to string in IE9 – Juan Stoppa Jun 25 '14 at 10:55
5

This worked for me (credit: http://www.ibm.com/developerworks/xml/tutorials/x-processxmljquerytut/section3.html):

 function getXmlAsString(xmlDom){
      return (typeof XMLSerializer!=="undefined") ? 
           (new window.XMLSerializer()).serializeToString(xmlDom) : 
           xmlDom.xml;
 }          

Here's an example that retrieves information about a column from a SharePoint list:

var soapEnv =
    "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
        <soapenv:Body> \
             <GetList xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                <rowLimit>0</rowLimit> \
                <listName>Announcements</listName> \
            </GetList> \
        </soapenv:Body> \
    </soapenv:Envelope>";


jQuery.support.cors = true; 
$.ajax({
    url: "http://sharepoint/_vti_bin/lists.asmx",
    type: "POST",
    dataType: "xml",
    data: soapEnv,
    contentType: "text/xml; charset=\"utf-8\"",
    complete: function(xData){
        var xmlDoc = $.parseXML(xData.responseText), $xml = $(xmlDoc)           
        $Fields = $xml.find("Field");
        $field = $Fields.filter("Field[Name='Title']")[0];

        //Show the xml
        alert(getXmlAsString( xmlDoc ));
        alert(getXmlAsString( $field ));
    }
});
Ben
  • 584
  • 9
  • 8
4

Had the same problem - xmlString was returning an empty string. Adding [0] to jQuery selector helped to address XML-type object:

Your Javascript:

<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[0]);
    }
    return xmlString;
}   
</script>

jQuery:

<script>
$(function(){ 
  xmlData = "<tag>just a sample here</tag>"; 
  xmlData= $(xmlData); 
  if (window.ActiveXObject){ 
    var xmlString = xmlData.xml; 
  } else {
    var oSerializer = new XMLSerializer(); 
    var xmlString = oSerializer.serializeToString(xmlData[0]);
  } 
  console.log(xmlString); 
})
</script>
  • 1
    Actually, to properly parse XML with jQuery you want to use `jQuery.parseXML(xml)`. – Alexis Wilke Jan 29 '15 at 07:01
  • after let inputXObject = $.parseXML(...) created an object, (new XMLSerializer()).serializeToString(inputXObject) returns just xml, not formatted (windows 7, Chrome, Chrome console as well) – Sasha Bond Jun 10 '18 at 18:55
1

You can use following function:

function getXmlString($xmlObj)
{   
    var xmlString="";
    $xmlObj.children().each(function(){
        xmlString+="<"+this.nodeName+">";
        if($(this).children().length>0){
            xmlString+=getXmlString($(this));
        }
        else
            xmlString+=$(this).text();
        xmlString+="</"+this.nodeName+">";
    });
    return xmlString;
}

Pass jquery xml object to this function

Sujan Shrestha
  • 191
  • 1
  • 4
  • this will have terrible performance with large trees. If you insist on serializing yourself the you should push the text fragments into an array and only `.join('')` once at the end. – epeleg Jul 22 '13 at 07:22
0

function serializeXML(xmldom) {
  if (typeof XMLSerializer != "undefined") {
    return (new XMLSerializer()).serializeToString(xmldom);
  } else if (typeof xmldom.xml != "undefined") {
    return xmldom.xml;
  } else {
    throw new Error("Could not serialize XML DOM.");
  }
}

// test
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
  xmlDoc = $.parseXML(xml),
  xmlStr = serializeXML(xmlDoc);
console.log("xmlStr: " + xmlStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Bo Hu
  • 1
  • 1
-1

In my case

if(window.ActiveXObject){
    xmlString = xmlData.xml;
}

Is not working. This is issue with IE10.

So I am able to fix this issue as follows:

if(window.ActiveXObject){
    xmlString = xmlData.attr('xml');
}

And working fine with any browser.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
-1

An old post I know but thought I would suggest this:

xml[0].outerHTML
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Mr AH
  • 1,100
  • 3
  • 11
  • 23
-2

Just access xml as attribute value of jQuery object. as simple as that.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156