Skip to main content
The 2024 Developer Survey results are live! See the results
adding sample showing that XML source in an HTML script element survives HTML parsing and can be parsed as XML afterwards by JavaScript/DOMParser
Source Link
Martin Honnen
  • 165.4k
  • 6
  • 94
  • 116

I don't think this has anything to do with XSLT, if you let an HTML parser parse markup like the one you showed then it parses into an HTML object element containing an HTML img element.

document.getElementById('test').innerHTML = `<object><image><\/image><\/object>`;
console.log(document.getElementById('test'));
console.log(document.getElementById('test').outerHTML);
<div id="test"></div>

So don't expect to be able to parse and preserve XML by parsing it as HTML5.

You can store XML in an HTML script element and read out its .text property:

var scriptElement = document.getElementById('test');

console.log(scriptElement.text);

var xmlDoc = new DOMParser().parseFromString(scriptElement.text, 'application/xml');

console.log(xmlDoc);
<script id="test" type="application/xml"><object><image></image></object></script>

I don't think this has anything to do with XSLT, if you let an HTML parser parse markup like the one you showed then it parses into an HTML object element containing an HTML img element.

document.getElementById('test').innerHTML = `<object><image><\/image><\/object>`;
console.log(document.getElementById('test'));
console.log(document.getElementById('test').outerHTML);
<div id="test"></div>

So don't expect to be able to parse and preserve XML by parsing it as HTML5.

I don't think this has anything to do with XSLT, if you let an HTML parser parse markup like the one you showed then it parses into an HTML object element containing an HTML img element.

document.getElementById('test').innerHTML = `<object><image><\/image><\/object>`;
console.log(document.getElementById('test'));
console.log(document.getElementById('test').outerHTML);
<div id="test"></div>

So don't expect to be able to parse and preserve XML by parsing it as HTML5.

You can store XML in an HTML script element and read out its .text property:

var scriptElement = document.getElementById('test');

console.log(scriptElement.text);

var xmlDoc = new DOMParser().parseFromString(scriptElement.text, 'application/xml');

console.log(xmlDoc);
<script id="test" type="application/xml"><object><image></image></object></script>

Source Link
Martin Honnen
  • 165.4k
  • 6
  • 94
  • 116

I don't think this has anything to do with XSLT, if you let an HTML parser parse markup like the one you showed then it parses into an HTML object element containing an HTML img element.

document.getElementById('test').innerHTML = `<object><image><\/image><\/object>`;
console.log(document.getElementById('test'));
console.log(document.getElementById('test').outerHTML);
<div id="test"></div>

So don't expect to be able to parse and preserve XML by parsing it as HTML5.