Derk Arts
Derk Arts

Reputation: 3460

Create XML using JS and convert to string

I'm trying to convert form values into XML. The whole script worked fine in Chrome etc, but IE8 had to ruin it, of course. I first had to change my code because IE was throwing errors on the append function (apparently I had created HTML elements instead of XML elements. So now I think it's all XML and IE is not whining anymore. However, when I'm trying to convert the XML to a string, both Chrome and IE return undefined (chrome actually shows a blank line in the console.

What am I doing wrong?

 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;
}   


function saveValues(thisB,formName){
       var xpath = $(thisB).attr("xpath");
       var returnToServer = $(thisB).attr("returnToServer");
       var version = $(thisB).attr("version");
       var now= Math.round(new Date().getTime() / 1000)
       var $root = $($.parseXML("<XMLDocument />").getElementsByTagName('*')[0]);
       var $valuesEl = $($.parseXML('<saveValues xpath="'+xpath+'" returnToServer="'+returnToServer+'" version="'+version+'"></saveValues>').getElementsByTagName('*')[0]);
           $("input").each(function(){
           var name = $(this).attr("name");
               if(name != 'xmlToPost'+formName && name != 'saveValuesButton'){
                   if( $(this).attr("type") == 'text'  || (($(this).attr("type") == 'checkbox' || $(this).attr("type") == 'radio') && $(this).is(":checked"))){
                       $valueEl = $($.parseXML('<value datetime="'+now+'" version="'+version+'" name="'+name+'"></value>').getElementsByTagName('*')[0]);
                       $valuesEl.append($valueEl);
                }
           }
       });

        $root.append($valuesEl);
        var valuesXML = xmlToString($root);
        var postToXMLContent = $("#xmlToPost"+formName).val();
        valuesXML = valuesXML.replace(/savevalues/gi,"saveValues");
        valuesXML = valuesXML.replace("returntoserver","returnToServer");
        //..rest of code
    }

When I log the $root object, Chrome gives me a big object that starts with [<xmldocument>, context: <xmldocument>], which I can expand to find childnodes, that contains saveValues etc. IE just shows [object Object].

Upvotes: 0

Views: 1060

Answers (1)

Bergi
Bergi

Reputation: 664297

An XML serializer expects an XML document, not a jQuery wrapper (which you can see logged in Chrome). So use xmlToString($root[0]);.

Anyway, as jQuery obviously seems not to be designed to work with XML, I can only recommend to use plain DOM methods. It would make your code much shorter.

Upvotes: 1

Related Questions