Parsing and serializing XML

From MozillaZine Knowledge Base

Revision as of 20:28, 10 March 2005; view current revision
←Older revision | Newer revision→

Mozilla doesn't support the W3C's Document Object Model Load and Save at this moment, so the easiest way to serialize and deserialize DOM trees is to use the following Mozilla-specific interfaces:

  • XMLSerializer to serialize DOM trees to strings or to files
  • DOMParser to parse XML from strings into DOM trees
  • XMLHttpRequest to parse XML from files into DOM trees. Although DOMParser does have a method named parseFromStream(), it's actually easier to use XMLHttpRequest which works for remote and local files.


Serializing DOM trees to strings

First, create a DOM tree using code like this.

Now, let's serialize doc — the DOM tree — to a string:

var serializer = new XMLSerializer();
var xml = serializer.serializeToString(doc);

Serializing DOM trees to files

First, create a DOM tree using code like this.

Now, let's serialize doc — the DOM tree — to a file (you can read more about using files in Mozilla here):

var serializer = new XMLSerializer();
var foStream = Components.classes[";1"]
var file = Components.classes[";1"]
           .get("ProfD", Components.interfaces.nsIFile); // get profile folder
file.append("extensions");   // extensions sub-directory
file.append("{5872365E-67D1-4AFD-9480-FD293BEBD20D}");   // GUID of your extension
file.append("myXMLFile.xml");   // filename
foStream.init(file, 0x02 | 0x08 | 0x20, 0664, 0);   // write, create, truncate
serializer.serializeToFile(doc, foStream, "IS0-8859-1");   // rememeber, doc is the DOM tree

Parsing strings into DOM trees

var theString='<a id="a"><b id="b">hey!</b></a>';
var parser = new DOMParser();
var dom = parser.parseFromString(theString, "text/xml");

Parsing files into DOM trees

Coming soon