undefined: undefined error when calling XSLTProcessor.prototype.importStylesheet

做~自己de王妃 提交于 2020-04-16 03:28:28

问题


I want to prettify some XML, and I found following code (in this answer, JSFiddle). I modified it like this:

const xsltDoc = new DOMParser().parseFromString([
    // describes how we want to modify the XML - indent everything
    '<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">',
    '  <xsl:output omit-xml-declaration="yes" indent="yes"/>',
    '    <xsl:template match="node()|@*">',
    '      <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>',
    '    </xsl:template>',
    '</xsl:stylesheet>',
].join('\n'), 'application/xml');
function prettifyXml(sourceXml) {
    var xmlDoc = new DOMParser().parseFromString(sourceXml, 'application/xml');
    var xsltProcessor = new XSLTProcessor();
    // Error happens here:
    xsltProcessor.importStylesheet(xsltDoc);
    var resultDoc = xsltProcessor.transformToDocument(xmlDoc);
    var resultXml = new XMLSerializer().serializeToString(resultDoc);
    return resultXml;
};

I get an error running the code, but the error has no message. It looks like this in Firefox console:

And this is what I see in debugger:

The error does also happen in the Fiddle from the original answer. I would like to know what kind of error is this and how to fix it.

I am including Firefox tag, because I think this is not a normal browser behavior. My version is 61.0.2 (64-bit).


回答1:


In terms of XSLT you need a version attribute on the root element of the stylesheet so try <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">. This seems to fix the error on the importStylesheet call, see https://jsfiddle.net/sgeryvyu/361/.

On the other hand, Firefox/Mozilla's XSLT processor is known to do a tree to tree transformation so with transformToDocument and Mozilla you won't get any serialization options of xsl:output applied, meaning that attempt to push your DOM tree through an XSLT simply gives you another DOM tree without the wanted indentation.



来源:https://stackoverflow.com/questions/51989864/undefined-undefined-error-when-calling-xsltprocessor-prototype-importstylesheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!