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:
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?
Removing the linebreak between <script ...>
and <?xml version="1.0" encoding="UTF-8"?>
fixed the error for me