I have XML document that was parsed to DOM object like this:
const contentDoc = new DOMParser().parseFromString(data, "text/xml");
How can I add/prepend following xml-stylesheet directive to it?
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
I want to visualize provided XML file using XSLT stylesheet (that is also provided for me) and I do not want to play with strings (I could potentially just add this declaration with simple string operations before the XML becomes DOM) but I would like to do this properly.
CodePudding user response:
You will need to use XSLTProcessor() method to import the Stylesheet. After you import the XSL, transform the xml to fragment with "transformToFragment()" or "transformToFragment()" to transform the document with your XSL.
After all, you just add the transformed fragment/document to your desired element.
Refer to this example on MDN Also this can help you understand the use of transformation
I replicated the example they have and is working properly based on your needs, this can solve your request.
This is what they do:
function Init(){
// load the xslt file, example1.xsl
var myXMLHTTPRequest = new XMLHttpRequest();
myXMLHTTPRequest.open("GET", "example1.xsl", false);
myXMLHTTPRequest.send(null);
xslStylesheet = myXMLHTTPRequest.responseXML;
xsltProcessor.importStylesheet(xslStylesheet);
// load the XML file, example1.xml
myXMLHTTPRequest = new XMLHttpRequest();
myXMLHTTPRequest.open("GET", "example1.xml", false);
myXMLHTTPRequest.send(null);
xmlDoc = myXMLHTTPRequest.responseXML;
var fragment = xsltProcessor.transformToFragment(xmlDoc, document);
document.getElementById("example").textContent = "";
myDOM = fragment;
document.getElementById("example").appendChild(fragment);
}
Init();