XSLTProcessor: transformToDocument() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Phương thức transformToDocument() của giao diện XSLTProcessor biến đổi Node nguồn được cung cấp thành Document bằng cách sử dụng biểu định kiểu XSLT liên kết với XSLTProcessor.

Cú pháp

js
transformToDocument(source)

Tham số

source

Node nguồn để áp dụng biểu định kiểu XSLT lên.

Giá trị trả về

Một Document. Giao diện thực tế phụ thuộc vào phương thức xuất của biểu định kiểu, được chỉ định bởi thuộc tính method của phần tử <xsl:output>.

Phương thức xuất Giao diện kết quả
html HTMLDocument
xml XMLDocument
text XMLDocument với một phần tử gốc duy nhất <transformiix:result> chứa văn bản như phần tử con

Ví dụ

Sử dụng transformToDocument()

Ví dụ này minh họa cách sử dụng transformToDocument() để biến đổi một tài liệu XML bằng XSLT, tạo ra một cấu trúc tài liệu XML mới.

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;

Kết quả

Thông số kỹ thuật

Thông số kỹ thuật
DOM
# dom-xsltprocessor-transformtodocument

Tương thích trình duyệt

Xem thêm