XSLTProcessor: transformToDocument() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

XSLTProcessor 介面的 transformToDocument() 方法使用與 XSLTProcessor 關聯的 XSLT 樣式表,將提供的 Node 源轉換為 Document

語法

js
transformToDocument(source)

引數

source

要應用 XSLT 樣式表的 Node 源。

返回值

一個 Document。實際介面取決於樣式表的輸出方法,如 <xsl:output> 元素的 method 屬性所指定的。

輸出方法 結果介面
html HTMLDocument
xml XMLDocument
文字 帶有單個根元素 <transformiix:result>XMLDocument,文字作為其子節點。

示例

使用 transformToDocument()

此示例演示瞭如何使用 transformToDocument() 透過 XSLT 轉換 XML 文件,從而生成新的 XML 文件結構。

HTML

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

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="xml" indent="yes"/>
  <xsl:template match="/">
    <catalog>
      <xsl:for-each select="books/book">
        <item>
          <name><xsl:value-of select="title"/></name>
          <writer><xsl:value-of select="author"/></writer>
        </item>
      </xsl:for-each>
    </catalog>
  </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 new XML document
const resultDoc = xsltProcessor.transformToDocument(xmlDoc);

// Serialize the result document to a string
const serializer = new XMLSerializer();
const resultString = serializer.serializeToString(resultDoc);

// Display the transformed XML in the page
document.getElementById("result").textContent = resultString;

結果

規範

規範
DOM
# dom-xsltprocessor-transformtodocument

瀏覽器相容性

另見