Search code examples
javascriptjqueryxmlparsexml

Prevent jQuery from manipulating dynamically inserted XML strings


This answer briefly touched on this topic, but did not mention the problem I am having.

Take a look at this fiddle.

As you can see from the alert message, jQuery made a number of changes I was not expecting:

  • collapsed the original <node></node> into a self-closing tag (<node />)
  • $('<SelfClosingNode />') became <selfclosingnode xmlns="http://www.w3.org/1999/xhtml"></selfclosingnode>, eg. made the tag name lower-case, added the xmlns attribute, and split it into opening and closing tags

I need to be able to insert EXACT xml, i.o.w. I don't want jQuery to mess with my mark-up structure!

Thanks in advance for the help...


Solution

  • Good news is that you can force the case sensitivity for your SelfClosingNode. See below:

    var xml_string = $("#xml-data").html();
    try{
        var xml = $.parseXML(xml_string);
        var $xml = $(xml);
    
        var newStuff = $.parseXML("<SelfClosingNode />");
        var $newStuff = $(newStuff.documentElement);
        $xml.find("project").append($newStuff);
    
        console.log(xml.documentElement);    
    
        // Needed if you are running in IE
        if (window.ActiveXObject) {
          var new_xml_string = xml.xml;
        } else {
          var new_xml_string = (new XMLSerializer()).serializeToString(xml);
        }
    
        alert( new_xml_string );
    
    } catch(e){
    
        alert(e);
    
    }
    

    Unfortunately, it is the XMLSerializer that is forcing the self closing tags, not JQuery. Self closing tags are considered valid for XML, but not for XHTML. If you look into the console log output (see the console.log statement above) you can see that the tags are not actually self-closed in the DOM.

    One quick and dirty way is to change <node></node> to <node><!-- comment --></node>.

    Otherwise your external program may have to be made more flexible to read these self-closing tags, as they are valid XML. There are some questions on replacing self-closing tags in existing XML, e.g. Replace XML self-closing tag with empty one