Parsing and serializing XML: Difference between revisions

From MozillaZine Knowledge Base
Jump to navigationJump to search
(added io.js section)
No edit summary
Line 1: Line 1:
Mozilla [https://bugzilla.mozilla.org/show_bug.cgi?id=155749 doesn't support] the W3C's [http://www.w3.org/TR/DOM-Level-3-LS/load-save.html 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:
Mozilla [https://bugzilla.mozilla.org/show_bug.cgi?id=155749 doesn't support] the W3C's [http://www.w3.org/TR/DOM-Level-3-LS/load-save.html 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:


*[http://www.xulplanet.com/references/objref/XMLSerializer.html XMLSerializer] to serialize '''DOM trees to strings or to files'''
*[http://xulplanet.com/references/objref/XMLSerializer.html XMLSerializer] to serialize '''DOM trees to strings or to files'''
*[http://xulplanet.com/references/objref/DOMParser.html DOMParser] to parse XML from '''strings into DOM trees'''
*[http://xulplanet.com/references/objref/DOMParser.html DOMParser] to parse XML from '''strings into DOM trees'''
*[http://xulplanet.com/references/objref/XMLHttpRequest.html XMLHttpRequest] to parse XML from '''files into DOM trees'''. Although <code>[http://xulplanet.com/references/objref/DOMParser.html DOMParser]</code> does have a method named <code>[http://xulplanet.com/references/objref/DOMParser.html#method_parseFromStream parseFromStream()]</code>, it's actually easier to [[XMLHttpRequest|use XMLHttpRequest]] which  works for remote '''and''' local files.
*[http://xulplanet.com/references/objref/XMLHttpRequest.html XMLHttpRequest] to parse XML from '''files into DOM trees'''. Although <code>[http://xulplanet.com/references/objref/DOMParser.html DOMParser]</code> does have a method named <code>[http://xulplanet.com/references/objref/DOMParser.html#method_parseFromStream parseFromStream()]</code>, it's actually easier to [[XMLHttpRequest|use XMLHttpRequest]] which  works for remote '''and''' local files.
Line 47: Line 47:
==Parsing files into DOM trees==
==Parsing files into DOM trees==
===XMLHttpRequest===
===XMLHttpRequest===
As was previously mentioned, even though <code>[http://xulplanet.com/references/objref/DOMParser.html DOMParser]</code> does have a method named <code>[http://xulplanet.com/references/objref/DOMParser.html#method_parseFromStream parseFromStream()]</code>, it's easier to [[XMLHttpRequest|use XMLHttpRequest]]. That's what we'll demonstrate here.
As was previously mentioned, even though <code>[http://xulplanet.com/references/objref/DOMParser.html DOMParser]</code> does have a method named <code>[http://xulplanet.com/references/objref/DOMParser.html#method_parseFromStream parseFromStream()]</code>, it's easier to use [[XMLHttpRequest]]. That's what we'll demonstrate here.


First, read the local or remote XML file into a string:
First, read the local or remote XML file into a string:
Line 55: Line 55:
req.send(null);
req.send(null);
</pre>
</pre>
The <code>foo-bar</code> argument of <code>[http://www.xulplanet.com/references/objref/XMLHttpRequest.html#method_open XMLHttpRequest.open()]</code> specifies the HTTP method to use if the URL (the second argument) is an HTTP(S) URL. Since we're using a <code>chrome://</code> URL, the first argument to <code>[http://www.xulplanet.com/references/objref/XMLHttpRequest.html#method_open XMLHttpRequest.open()]</code> is ignored. You should change this to GET/POST/PUT/DELETE/OPTIONS/TRACE/HEAD if using an HTTP(S) URL.
The <code>foo-bar</code> argument of <code>[http://xulplanet.com/references/objref/XMLHttpRequest.html#method_open XMLHttpRequest.open()]</code> specifies the HTTP method to use if the URL (the second argument) is an HTTP(S) URL. Since we're using a <code>chrome://</code> URL, the first argument to <code>[http://xulplanet.com/references/objref/XMLHttpRequest.html#method_open XMLHttpRequest.open()]</code> is ignored. You should change this to GET/POST/PUT/DELETE/OPTIONS/TRACE/HEAD if using an HTTP(S) URL.


Now that we have the XML as a string (in <code>req.responseText</code>), we can use the code similar to that in [#Parsing strings into DOM trees] to get the XML into a DOM tree:
Now that we have the XML as a string (in <code>req.responseText</code>), we can use the code similar to that in [[Parsing and serializing XML#Parsing strings into DOM trees|Parsing strings into DOM trees]] to get the XML into a DOM tree:
<pre>
<pre>
var parser = new DOMParser();
var parser = new DOMParser();
Line 71: Line 71:
file.append("{5872365E-67D1-4AFD-9480-FD293BEBD20D}");
file.append("{5872365E-67D1-4AFD-9480-FD293BEBD20D}");
file.append("people.xml");
file.append("people.xml");
var fileContents = FileIO.read(sysBin);
var fileContents = FileIO.read(file);
var domParser = new DOMParser();
var domParser = new DOMParser();
domParser.parseFromString(fileContents);
var doc = domParser.parseFromString(fileContents);
// print the name of the root element
// print the name of the root element
dump(dom.documentElement.nodeName);
dump(doc.documentElement.nodeName);
</pre>
</pre>
[[Category:Example code]] [[Category:XML in Javascript]]
[[Category:Example code]] [[Category:XML in Javascript]]

Revision as of 23:16, 10 March 2005

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:


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["@mozilla.org/network/file-output-stream;1"]
               .createInstance(Components.interfaces.nsIFileOutputStream);
var file = Components.classes["@mozilla.org/file/directory_service;1"]
           .getService(Components.interfaces.nsIProperties)
           .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
foStream.close();

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");
// print the name of the root element
dump(dom.documentElement.nodeName);

Parsing files into DOM trees

XMLHttpRequest

As was previously mentioned, even though DOMParser does have a method named parseFromStream(), it's easier to use XMLHttpRequest. That's what we'll demonstrate here.

First, read the local or remote XML file into a string:

var req = new XMLHttpRequest();
req.open("foo-bar!", "chrome://passwdmaker/content/people.xml", false); 
req.send(null);

The foo-bar argument of XMLHttpRequest.open() specifies the HTTP method to use if the URL (the second argument) is an HTTP(S) URL. Since we're using a chrome:// URL, the first argument to XMLHttpRequest.open() is ignored. You should change this to GET/POST/PUT/DELETE/OPTIONS/TRACE/HEAD if using an HTTP(S) URL.

Now that we have the XML as a string (in req.responseText), we can use the code similar to that in Parsing strings into DOM trees to get the XML into a DOM tree:

var parser = new DOMParser();
var dom = parser.parseFromString(req.responseText, "text/xml");
// print the name of the root element
dump(dom.documentElement.nodeName);

io.js

If you prefer io.js, this code will also parse a file into a DOM tree. Unlike XMLHttpRequest, it will not work with remote files:

var file = DirIO.get("ProfD"); // %Profile% dir
file.append("extensions");
file.append("{5872365E-67D1-4AFD-9480-FD293BEBD20D}");
file.append("people.xml");
var fileContents = FileIO.read(file);
var domParser = new DOMParser();
var doc = domParser.parseFromString(fileContents);
// print the name of the root element
dump(doc.documentElement.nodeName);