Processing XML with JavaScript

Simon Willison
Simon Willison
Published in
·Updated:

Share this article

SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools

7 Day Free Trial. Cancel Anytime.

I came across a situation at work today where I needed to take an XML string from a textarea and perform DOM manipulations on it using JavaScript. After some digging around, I remembered an open source library called Sarissa I had checked out a few days ago. Sarissa is a remarkably useful piece of code: it offers a unified interface in both Internet Explorer and Mozilla for handling HTTP requests, processing XML documents and fragments and performing XSLT transformations. The IE functions are mostly provided using ActiveX objects, while the Mozilla functions take advantage of Mozilla’s XML Extras package.

Using Sarissa, converting a string containing XML in to a regular DOM node can be done using the following:


var dom = Sarissa.getDomDocument();
var xml = 'This is XML!';
dom.loadXML(xml);

‘dom’ can then be treated as a DOM node, and manipulated using the regular DOM API functions (appendChild, childNodes and so on). To convert the node back to XML, simply access it’s ‘xml’ property:


var xml_again = dom.xml;

Sarissa has one disadvantage: the library itself is a hefty 24 KB. As the application I’m working on only needs to work with Mozilla, I decided to dig in to the Sarissa source code to see how the above could be achieved without the compatibility layer. Here’s the equivalent Mozilla specific code, making direct calls to additional classes provided by Mozilla’s XML extras:


var xml = 'This is XML!';
var dom = (new DOMParser()).parseFromString(xml, "text/xml");

And to convert back to a string:


var xml_again = (new XMLSerializer()).serializeToString(dom);

Unfortunately, as far as I can tell the only official documentation for the XML extras package takes the form of a test suite.

Share this article

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.