The Web platform provides the following objects for parsing and serializing XML:
- XMLSerializer to serialize DOM trees to strings
- XPath to address (point to) different parts of an XML document (through a non-XML syntax) into strings
- DOMParser to parse XML from strings into DOM trees
- XMLHttpRequest to parse URL-addressable resources into DOM trees
Part 1: how to create an XML document
In this section we will try to create an XML document (which is an instance of Document
) starting from different points.
Parsing strings into DOM trees
Building an XML document starting from a JavaScript Object tree (JXON)
Please, see the JXON reverse algorithms.
Parsing URL-addressable resources into DOM trees
Using XMLHttpRequest
Here is sample code which reads and parses an URL-addressable XML file into a DOM tree:
var xhr = new XMLHttpRequest(); xhr.onload = function() { dump(xhr.responseXML.documentElement.nodeName); } xhr.onerror = function() { dump("Error while getting XML."); } xhr.open("GET", "example.xml"); xhr.responseType = "document"; xhr.send();
xhr.responseXML
is a Document
instance.
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 oFile = DirIO.get("ProfD"); // %Profile% dir oFile.append("extensions"); oFile.append("{5872365E-67D1-4AFD-9480-FD293BEBD20D}"); oFile.append("people.xml"); oDOM = (new DOMParser()).parseFromString(FileIO.read(oFile), "text/xml"); // print the name of the root element or error message dump(oDOM.documentElement.nodeName == "parsererror" ? "error while parsing" : oDOM.documentElement.nodeName);
Part 2: how to serialize the content of a given XML document
In this section we already have a parsed XML document (that is, an instance of {{ domxref("Document") }}) and want to use its content.
Serializing DOM trees to strings
First, create a DOM tree as described in How to Create a DOM tree. Alternatively, use a DOM tree obtained from {{ domxref("XMLHttpRequest") }}.
Now, let's serialize doc
— the DOM tree — to a string:
var oSerializer = new XMLSerializer(); var sXML = oSerializer.serializeToString(doc);
From within a JS XPCOM component (or a JS module), new XMLSerializer()
is not available. Instead, write:
var oSerializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"] .createInstance(Components.interfaces.nsIDOMSerializer); var sXML = oSerializer.serializeToString(doc);
"Pretty" serialization of DOM trees to strings
You can pretty print a DOM tree using XMLSerializer
and E4X. First, create a DOM tree as described in the How to Create a DOM tree article. Alternatively, use a DOM tree obtained from {{ domxref("XMLHttpRequest") }}. We assume it's in the doc
variable.
var oSerializer = new XMLSerializer(); var sPrettyXML = XML(oSerializer.serializeToString(doc)).toXMLString();
Indents are provided with two spaces. You can, of course, use {{ domxref("treeWalker") }} to write your own, more performant version which also has the advantage that you can customize the indent string to be whatever you like.
toXMLString
method your CDATA elements will be lost and only the containing text remains. So using the above method might not be useful if you have CDATA elements in your XML.<content><![CDATA[This is the content]]></content>
Will become
<content>This is the content</content>
Serializing DOM trees to Javascript Object trees (JXON)
JXON (lossless JavaScript XML Object Notation) is a generic name by which is defined the representation of JavaScript Objects using XML. If you are interested to address only some parts of an XML document, use XPath instead of converting the whole document into JSON! Otherwise, read the article about JXON.
Serializing DOM trees to files
First, create a DOM tree as described in the How to Create a DOM tree article. If you have already have a DOM tree from using {{ domxref("XMLHttpRequest") }}, skip to the end of this section.
Now, let's serialize doc
— the DOM tree — to a file (you can read more about using files in Mozilla):
var oFOStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream); var oFile = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsILocalFile); // get profile folder oFile.append("extensions"); // extensions sub-directory oFile.append("{5872365E-67D1-4AFD-9480-FD293BEBD20D}"); // GUID of your extension oFile.append("myXMLFile.xml"); // filename oFOStream.init(oFile, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate (new XMLSerializer()).serializeToStream(doc, oFOStream, ""); // rememeber, doc is the DOM tree oFOStream.close();
Serializing XMLHttpRequest objects to files
If you already have a DOM tree from using {{ domxref("XMLHttpRequest") }}, use the same code as above but replace serializer.serializeToStream(doc, oFOStream, "")
with serializer.serializeToStream(xmlHttpRequest.responseXML.documentElement, oFOStream, "")
where xmlHttpRequest
is an instance of XMLHttpRequest
.
Note that this first parses the XML retrieved from the server, then re-serializes it into a stream. Depending on your needs, you could just save the xmlHttpRequest.responseText
directly.
See also
{{ languages( {"ja": "ja/Parsing_and_serializing_XML","zh-cn": "zh-cn/Parsing_and_serializing_XML", "it": "it/Costruire_e_decostruire_un_documento_XML" } ) }}