MozillaZine

Parsing and serializing XML

From MozillaZine Knowledge Base

(Difference between revisions)
Revision as of 23:28, 26 September 2006
Np (Talk | contribs)
(→Serializing XMLHttpRequest objects to files - update link to XHR)
<-- Previous diff
Revision as of 21:38, 7 November 2006
Grimholtz (Talk | contribs)
(moved to MDC)
Next diff -->
Line 1: Line 1:
-{{extdev}}+Moved [[http://developer.mozilla.org/en/docs/Parsing_and_serializing_XML here]] (MDC).
- +
-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://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://developer.mozilla.org/en/docs/XMLHttpRequest XMLHttpRequest] to parse XML from '''files into DOM trees'''. Although <code>DOMParser</code> does have a method named <code>parseFromStream()</code>, it's actually easier to [http://developer.mozilla.org/en/docs/XMLHttpRequest XMLHttpRequest] which works for remote '''and''' local files.+
- +
- +
-==Serializing DOM trees to strings==+
-First, create a DOM tree using code [[How to Create a DOM tree| like this]].+
- +
-Now, let's serialize <code>doc</code> &mdash; the DOM tree &mdash; to a string:+
- +
-<pre>+
-var serializer = new XMLSerializer();+
-var xml = serializer.serializeToString(doc);+
-</pre>+
- +
-==Serializing DOM trees to files==+
-First, create a DOM tree using code [[How to Create a DOM tree| like this]]. If you have already have a DOM tree from using [http://developer.mozilla.org/en/docs/XMLHttpRequest XMLHttpRequest], skip to the end of this section.+
- +
-Now, let's serialize <code>doc</code> &mdash; the DOM tree &mdash; to a file (you can read more [[File IO|about using files in Mozilla]]):+
- +
-<pre>+
-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.serializeToStream(doc, foStream, ""); // rememeber, doc is the DOM tree+
-foStream.close();+
-</pre>+
- +
-==Serializing XMLHttpRequest objects to files==+
-If you have already have a DOM tree from using [http://developer.mozilla.org/en/docs/XMLHttpRequest XMLHttpRequest], use the same code as above but replace <code>serializer.serializeToStream(doc, foStream, "")</code> with <code>serializer.serializeToStream(xmlHttpRequest.responseText, foStream, "")</code> where <code>xmlHttpRequest</code> is an instance of XMLHttpRequest.+
- +
-==Parsing strings into DOM trees==+
-<pre>+
-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 or error message+
-dump(dom.documentElement.nodeName == "parsererror" ? "error while parsing" : dom.documentElement.nodeName);+
-</pre>+
- +
-==Parsing files into DOM trees==+
-===XMLHttpRequest===+
-As was previously mentioned, even though <code>DOMParser</code> does have a method named <code>parseFromStream()</code>, it's easier to use [http://developer.mozilla.org/en/docs/XMLHttpRequest XMLHttpRequest] to parse XML files into DOM trees (XMLHttpRequest works for both local and remote files). Here is sample code which reads and parses a local XML file into a DOM tree:+
- +
-<pre>+
-var req = new XMLHttpRequest();+
-req.open("GET", "chrome://passwdmaker/content/people.xml", false); +
-req.send(null);+
-// print the name of the root element or error message+
-var dom = req.responseXML;+
-dump(dom.documentElement.nodeName == "parsererror" ? "error while parsing" : dom.documentElement.nodeName);+
-</pre>+
- +
-<code>req.responseXML</code> is a <code>[http://xulplanet.com/references/objref/Document.html Document]</code> instance.+
- +
-===io.js===+
-If you prefer [[io.js]], this code will also parse a file into a DOM tree. Unlike <code>XMLHttpRequest</code>, it will not work with remote files:+
-<pre>+
-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, "text/xml");+
-// print the name of the root element or error message+
-dump(dom.documentElement.nodeName == "parsererror" ? "error while parsing" : dom.documentElement.nodeName);+
-</pre>+
- +
-==Resources==+
-* [https://sourceforge.net/projects/sarissa/ Sarissa] - Sarissa is a cross-browser ECMAScript library for client side XML manipulation, including loading XML from URLs or strings, performing XSLT transformations, XPath queries and more. Supported: Gecko (Mozilla, Firefox etc), IE, KHTML (Konqueror, Safari). If you're writing JavaScript that is used in both XUL applications and HTML pages, and the HTML pages may be viewed in non-Gecko-based applications (such as Internet Explorer, Opera, Konqueror, Safari), you should consider using Sarissa to parse and/or serialize XML. ''Note:'' Do not create a DOM object using <code>document.implementation.createDocument()</code> and then use Sarissa classes and methods to manipulate that object. It will not work. You must use Sarissa to create the initial DOM object.+
-* [http://xulplanet.com/tutorials/mozsdk/xmlparse.php Parsing and Serializing XML at XulPlanet]+
- +
-[[Category:Example code]] [[Category:XML in JavaScript]]+

Revision as of 21:38, 7 November 2006

Moved [here] (MDC).