28

I have an XML object (loaded using XMLHTTPRequest's responseXML). I have modified the object (using jQuery) and would like to store it as text in a string.

There is apparently a simple way to do it in Firefox et al:

var xmlString = new XMLSerializer().serializeToString( doc );

(from rosettacode )

But how does one do it in IE6 and other browsers (without, of course, breaking Firefox)?

Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
Eero
  • 4,704
  • 4
  • 37
  • 40

1 Answers1

35

You can use doc.xml in internet exlporer.

You'll get something like this:

function xml2Str(xmlNode) {
   try {
      // Gecko- and Webkit-based browsers (Firefox, Chrome), Opera.
      return (new XMLSerializer()).serializeToString(xmlNode);
  }
  catch (e) {
     try {
        // Internet Explorer.
        return xmlNode.xml;
     }
     catch (e) {  
        //Other browsers without XML Serializer
        alert('Xmlserializer not supported');
     }
   }
   return false;
}

Found it here.

Huppie
  • 11,263
  • 4
  • 32
  • 34
  • Thanks... I finally found this after two days of searching. (It took me a while to realize that .xml was simply not there for FF/Chrome, I had assumed I was doing something wrong.) – Marcel Popescu Sep 04 '11 at 19:02
  • Webkit currently has a bug (e.g. in Chrome 19) and will not return correct XML: xmlNode = document.createElement('img'); xmlNode.src = "test.png" xmlNode.alt = "test" (new XMLSerializer()).serializeToString(xmlNode); Returns: "test" – cburgmer Jun 02 '12 at 19:33
  • @cburgmer that's not an xml node – Esailija Jul 20 '12 at 13:03
  • @Esailija I don't understand, what is it then? I expect XMLSerializer to serialize xmlNode into (note the trailing slash) – cburgmer Jul 24 '12 at 12:28
  • @cburgmer it's a html node, you created it using a html document. XML nodes don't have properties like `.src`. See what an actual xml element has with: `console.dir( document.implementation.createDocument( null, "xml", null ).createElement("img") )` – Esailija Jul 24 '12 at 13:11