I am experiencing an issue with transforming XML data using XSLT in JavaScript. My setup involves fetching XML data and an XSLT stylesheet, which is embedded within a tag in my HTML. When I try to transform the XML using XSLTProcessor, the result is null. This issue occurs when I access the XSLT from the tag, but not when I directly assign the XSLT as a string in my JavaScript code.
html:
<script id="xslt-code" type="text/xsl"> <!-- XSLT content here --> </script>
js:
async function fetchXMLAndApplyXSLT() {
// Fetch XML data...
const xsltCode = document.getElementById("xslt-code").textContent;
const xslParser = new DOMParser();
const xslStylesheet = xslParser.parseFromString(xsltCode, 'text/xml');
const xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xslStylesheet);
const transformedXML = xsltProcessor.transformToFragment(xmlDoc, document);
if (!transformedXML) {
console.error('Transformation resulted in null');
}
// Further processing...
}
Attempted Solutions:
- Ensured that the script tag has type="text/xsl".
- Checked that the script is executed after the DOM is fully loaded.
- Confirmed that textContent of the script tag returns the correct XSLT string.
Despite these efforts, transformedXML is still null. Directly assigning the XSLT as a string in JavaScript works fine, but fetching it from the tag doesn't.
Could anyone suggest what might be causing this issue or how to resolve it?
xml-stylesheetprocessing instruction?.texthtml.spec.whatwg.org/multipage/scripting.html#dom-script-text instead of.textContentfix it?