I need to create some XML using JavaScript. One of the more difficult things is that I need to populate the text content of a node with an XML qualified name. That is, a local name and prefix, such as myns:myelement.
The difficulty is that the XML document does not contain any other elements or attributes for the namespace to which the prefix should be bound. So I need to add a namespace node (xmlns) to the enclosing element, to define a prefix. For instance: -
<myElement xmlns:myprefix="http://something">myprefix:foo</myElement>
I can't see a nice way to add the xmlns namespace node in JavaScript. Currently, I have the following awful hack: -
// Hacky way to get a namespace prefix definition. TODO: can we do something nicer?
var prefix = "ixe";
requestElement.setAttributeNS(inputTypes[0].namespaceURL, prefix + ":" + "def", "");
inputElement.textContent = prefix + ":" + inputTypes[0].localName;
I'm creating an otherwise-unneeded attribute with the desired namespace and an arbitrary prefix. This causes the generated document to have an xmlns namespace node to define the prefix for the namespace.
On latest FireFox and Chrome, but not on IE, one can do inputElement.setAttribute("xmlns:" + PREFIX, inputType.namespaceUri);. But I want a browser-neutral solution.
But I'd much rather not create that dummy attribute. Surely, it must be possible to create the namespace node explicitly. What have I missed?