XSLTProcessor: transformToFragment() 方法

Baseline 已广泛支持

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

XSLTProcessor 接口的 transformToFragment() 方法使用与 XSLTProcessor 关联的 XSLT 样式表,将提供的 Node 源转换为 DocumentFragment

语法

js
transformToFragment(source, document)

参数

source

要应用 XSLT 样式表的 Node 源。

document

文档片段将与之关联的 Document。(任何文档片段都与其可以添加到的文档相关联)。

返回值

一个 DocumentFragment

示例

使用 transformToFragment()

本示例演示了如何使用 transformToFragment() 将 XML 数据转换为 HTML,然后可以直接将其作为文档片段插入 DOM 中。

HTML

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

JavaScript

js
const xmlString = `
<books>
  <book>
    <title>Book 1</title>
    <author>Author 1</author>
  </book>
  <book>
    <title>Book 2</title>
    <author>Author 2</author>
  </book>
</books>
`;

const xsltString = `
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <ul>
      <xsl:for-each select="books/book">
        <li>
          <strong><xsl:value-of select="title"/></strong>
          by <em><xsl:value-of select="author"/></em>
        </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();
xsltProcessor.importStylesheet(xsltDoc);

// Perform the transformation, returning the result as a document fragment
const resultFragment = xsltProcessor.transformToFragment(xmlDoc, document);

// Insert the result into the page
document.getElementById("result").appendChild(resultFragment);

结果

规范

规范
DOM
# dom-xsltprocessor-transformtofragment

浏览器兼容性

另见