XSLTProcessor: transformToFragment() 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 transformToFragment() của giao diện XSLTProcessor biến đổi một Node nguồn thành DocumentFragment bằng cách sử dụng biểu định kiểu XSLT liên kết với XSLTProcessor.
Cú pháp
js
transformToFragment(source, document)
Tham số
Giá trị trả về
Một DocumentFragment.
Ví dụ
>Sử dụng transformToFragment()
Ví dụ này minh họa cách sử dụng transformToFragment() để biến đổi dữ liệu XML thành HTML, sau đó có thể được chèn trực tiếp vào DOM dưới dạng đoạn tài liệu.
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);
Kết quả
Thông số kỹ thuật
| Specification |
|---|
| DOM> # dom-xsltprocessor-transformtofragment> |