0

I have one sample XML & XSL resource. I am getting XML as a string from API call in javascript. While XSLT is present as a static resource on the server. My goal is to display XML content along with stylesheet in HTML document element.

I do not want to use XSLTProcessor for now. I would like to try the browser way. And yes both the XML and XSLT would be coming from the same server.

Code:

import XSL from '@salesforce/resourceUrl/Roles';

export default class DisplayReport extends LightningElement {

    renderedCallback(){
        var xml = '<root> <node>one</node> <nodes> <node>1</node> <node>2</node> </nodes> <node>two</node> </root>'; 
        
        var output = '<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="'+XSL+'" ?>'+xml;
        console.log(output); //output on below line
        
        //<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/assets/project/b481ca5a6f/staticresources/Roles" ?><root> <node>one</node> <nodes> <node>1</node> <node>2</node> </nodes> <node>two</node> </root>
        
        var xmlNode = this.parseXml(output);        
        console.log(xmlNode);
        const element = this.template.querySelector('div.dms');
        element.appendChild(xmlNode.documentElement);
    }

    parseXml(xmlStr){
        if (window.DOMParser) {
            return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
        }
    }
}

Markup:

<template>
    <div class="dms" lwc:dom="manual">

    </div>
</template>

Output: (no style sheet getting applied)

one 1 2 two

Any idea what is missing here?

Shaggy
  • 5,422
  • 28
  • 98
  • 163
  • Why is XSLTProcessor not the browser way? – Martin Honnen Oct 24 '20 at 05:42
  • @MartinHonnen I am facing this issue https://salesforce.stackexchange.com/questions/302264/new-xsltprocessor-fails-in-lwc. Maybe it is because of shadow DOM. To answer your question, check this out https://stackoverflow.com/a/5722617/1169180 – Shaggy Oct 24 '20 at 06:03
  • I am not familiar with the tool or environment you use but if using DOMParser is the browser way and you have to use `new window.DOMParser()` in your environment then perhaps `new window.XSLTProcessor()` does work as well. The processing instruction will only work if you load an XML document from a server into a window or frame. – Martin Honnen Oct 24 '20 at 06:12
  • See https://stackoverflow.com/a/48881299 for using a `data:` URL with an iframe where both XML and XSLT are taken from a string. – Martin Honnen Oct 24 '20 at 06:45
  • I tried with `new window.XSLTProcessor()` but still it gives me an error `Error during LWC component connect phase: [Failed to construct 'XSLTProcessor': Please use the 'new' operator, this DOM object constructor cannot be called as a function.]` – Shaggy Oct 24 '20 at 18:44

0 Answers0