I have the following minimal JavaScript fragment:
var xml = '<El a:title="T" a:href="H" xmlns:a="http://www.w3.org/1999/xlink" />';
var dom = new DOMParser().parseFromString(xml, 'text/xml');
xml = new XMLSerializer().serializeToString(dom);
When I execute the code in most browsers (just paste it into your browser's JavaScript console), the parsed-then-serialized XML is equivalent to the original. For example on Chrome 8 I get:
<El xmlns:a="http://www.w3.org/1999/xlink" a:title="T" a:href="H"/>
However on Chrome 22 the same code fragment changes the XML to:
<El xmlns:a="http://www.w3.org/1999/xlink" xlink:title="T" xlink:href="H"/>
Note that the namespace prefix xlink
used by the title and href attributes is not defined anywhere, so the XML is now invalid. As you probably can imagine this causes all kinds of problems for code that tries to subsequently use the XML.
Is this a bug in the XMLSerializer or am I missing some intricacies about how the DOM should be serialized?
Also did anyone find a workaround that I can put in code, as opposed to make the XML match the apparent preference to use xlink
as the prefix for the XLink namespace?
Update
I did some additional testing and the problem seems to be caused by the fact that the XMLSerializer recognizes the XLink namespace and insists on outputting an xlink
prefix for it, without properly registering that prefix.
So this fragment work fine:
var xml = '<El a:title="T" a:href="H" xmlns:a="any-other-namespace-uri" />';
var dom = new DOMParser().parseFromString(xml, 'text/xml');
xml = new XMLSerializer().serializeToString(dom);
So here I changed the Namespace URL to something less well-known and the output is now valid:
<El xmlns:a="any-other-namespace-uri" a:title="T" a:href="H"/>
The following fragment also works fine:
var xml = '<El a:title="T" a:href="H" xmlns:a="http://www.w3.org/2000/xlink" />';
var dom = new DOMParser().parseFromString(xml, 'text/xml');
xml = new XMLSerializer().serializeToString(dom);
So in this case we use the "expected" prefix for the XLink namespace and it then serializes without problems:
<El xmlns:a="http://www.w3.org/2000/xlink" a:title="T" a:href="H"/>