XSLTProcessor: importStylesheet() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

XSLTProcessor 接口的 importStylesheet() 方法会为处理器导入一个 XSLT 样式表。

语法

js
importStylesheet(style)

参数

style

要导入的 Node。它可以是一个包含 XSLT 样式表的 XML 文档(这是一个具有 doctype 且其 name"xml"Document),或者是一个 字面量结果元素转换,或者是一个表示 <xsl:stylesheet><xsl:transform>Element

返回值

无(undefined)。

示例

使用 importStylesheet()

本示例演示了 importStylesheet() 如何将 XSLT 样式表加载到 XSLTProcessor 中,以便用于转换 XML 数据。

HTML

html
<div id="result"></div>

JavaScript

js
const xmlString = `
<items>
  <item>Item 1</item>
  <item>Item 2</item>
</items>
`;

const xsltString = `
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <ul>
      <xsl:for-each select="items/item">
        <li><xsl:value-of select="."/></li>
      </xsl:for-each>
    </ul>
  </xsl:template>
</xsl:stylesheet>
`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
const xsltDoc = parser.parseFromString(xsltString, "application/xml");

const xsltProcessor = new XSLTProcessor();

// Import the XSLT stylesheet into the XSLTProcessor
xsltProcessor.importStylesheet(xsltDoc);

// Perform the transformation from XML to HTML
const resultFragment = xsltProcessor.transformToFragment(xmlDoc, document);

// Display the transformed result in the page
document.getElementById("result").appendChild(resultFragment);

结果

规范

规范
DOM
# dom-xsltprocessor-importstylesheet

浏览器兼容性