XSLTProcessor: transformToDocument() 方法
XSLTProcessor 接口的 transformToDocument() 方法使用与 XSLTProcessor 关联的 XSLT 样式表,将提供的 Node 源转换为 Document。
语法
js
transformToDocument(source)
参数
返回值
一个 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 |
浏览器兼容性
加载中…