【问题标题】:undefined: undefined error when calling XSLTProcessor.prototype.importStylesheet未定义:调用 XSLTProcessor.prototype.importStylesheet 时出现未定义错误
【发布时间】:2018-08-23 15:57:54
【问题描述】:

我想美化一些 XML,我发现了以下代码 (in this answer, JSFiddle)。我是这样修改的:

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;
};

我在运行代码时遇到错误,但该错误没有消息。在 Firefox 控制台中看起来像这样:

这就是我在调试器中看到的:

错误也发生在原始答案中的小提琴中。我想知道这是什么错误以及如何修复它。

我包含 Firefox 标签,因为我认为这不是正常的浏览器行为。我的版本是 61.0.2(64 位)。

【问题讨论】:

    标签: javascript firefox xslt domparser


    【解决方案1】:

    就 XSLT 而言,您需要在样式表的根元素上添加 version 属性,因此请尝试使用 &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"&gt;。这似乎修复了importStylesheet 调用中的错误,请参阅https://jsfiddle.net/sgeryvyu/361/

    另一方面,众所周知,Firefox/Mozilla 的 XSLT 处理器会进行树到树的转换,因此对于 transformToDocument 和 Mozilla,您不会应用任何 xsl:output 的序列化选项,这意味着尝试推送您的 DOM通过 XSLT 构建的树只是为您提供另一个没有所需缩进的 DOM 树。

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 1970-01-01
      • 2021-10-25
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      相关资源
      最近更新 更多