Wednesday, April 08, 2009

CREATE XML DOCUMENT

/**
2 * Create a new Document object. If no arguments are specified,
3 * the document will be empty. If a root tag is specified, the document
4 * will contain that single root tag. If the root tag has a namespace
5 * prefix, the second argument must specify the URL that identifies the
6 * namespace.
7 */
8 XML.newDocument = function(rootTagName, namespaceURL) {
9 if (!rootTagName) rootTagName = "";
10 if (!namespaceURL) namespaceURL = "";
11 if (document.implementation && document.implementation.createDocument) {
12 // This is the W3C standard way to do it
13 return document.implementation.createDocument(namespaceURL, rootTagName, null);
14 }
15 else { // This is the IE way to do it
16 // Create an empty document as an ActiveX object
17 // If there is no root element, this is all we have to do
18 var doc = new ActiveXObject("MSXML2.DOMDocument");
19 // If there is a root tag, initialize the document
20 if (rootTagName) {
21 // Look for a namespace prefix
22 var prefix = "";
23 var tagname = rootTagName;
24 var p = rootTagName.indexOf(':');
25 if (p != -1) {
26 prefix = rootTagName.substring(0, p);
27 tagname = rootTagName.substring(p+1);
28 }
29 // If we have a namespace, we must have a namespace prefix
30 // If we don't have a namespace, we discard any prefix
31 if (namespaceURL) {
32 if (!prefix) prefix = "a0"; // What Firefox uses
33 }
34 else prefix = "";
35 // Create the root element (with optional namespace) as a
36 // string of text
37 var text = "<" + (prefix?(prefix+":"):"") + tagname +
38 (namespaceURL
39 ?(" xmlns:" + prefix + '="' + namespaceURL +'"')
40 :"") +
41 "/>";
42 // And parse that text into the empty document
43 doc.loadXML(text);
44 }
45 return doc;
46 }
47 };

0 comments: