DOMParser and XMLSerializer

This demo uses DOMParser and XMLSerializer to sync XML source with a live rendering in the DOM. These cross-browser APIs work with XML and the DOM much in the same way JSON works with JavaScript objects. DOMParser converts an XML string into a renderable DOM. Likewise, XMLSerializer converts any DOM node into an XML string, even HTML elements.

Edit the XML in the text area and click the left arrow button to use DOMParser to update the live rendering. Click on elements in the live rendering to delete them, then click the right arrow button to use XMLSerializer to update the XML source. You can also use the links below to switch between some pre-configured SVG and XHTML examples.

Pre-built Examples: SVG, XHTML

Click an element below to delete it or delete a random element, then click the right arrow button to update the source.

(Loading...)

Edit the XML source below, then click left arrow button to update the display.

The code below shows the implementation for the right and left arrow buttons. The highlighted lines illustrate how DOMParser and XMLSerializer are used by the demo.

// Left Arrow Button function updateDisplay() { var xml = _source.value; var parser = new DOMParser(); var doc = parser.parseFromString(xml, "text/xml"); var elm = document.adoptNode(doc.documentElement); _display.replaceChild(elm, _display.firstChild); } // Right Arrow Button function updateMarkup() { var elm = _display.firstChild; var serializer = new XMLSerializer(); var xml = serializer.serializeToString(elm); _source.value = xml; }

DOMParser can also be used with the responseText of an XMLHttpRequest, completing the JSON analogy. This is how each of the pre-built examples are loaded by this demo.

// Using DOMParser with XMLHttpRequest var parser = new DOMParser(); var xhr = new XMLHttpRequest(); ... var doc = parser.parseFromeString(xhr.responseText, "text/xml"); ...