XSLTProcessor: transformToFragment() 方法
XSLTProcessor 介面的 transformToFragment() 方法使用與 XSLTProcessor 關聯的 XSLT 樣式表,將提供的 Node 源轉換為 DocumentFragment。
語法
js
transformToFragment(source, 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 |
瀏覽器相容性
載入中…