XSLTProcessor: transformToDocument()-Methode

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.

Die transformToDocument()-Methode des XSLTProcessor-Interfaces transformiert die angegebene Node-Quelle in ein Document, indem sie das mit XSLTProcessor verbundene XSLT-Stylesheet verwendet.

Syntax

js
transformToDocument(source)

Parameter

source

Die Node-Quelle, auf die das XSLT-Stylesheet angewendet werden soll.

Rückgabewert

Ein Document. Das tatsächliche Interface hängt von der Ausgabemethode des Stylesheets ab, die durch das <xsl:output>-Element und dessen method-Attribut festgelegt wird.

Ausgabemethode Ergebnis-Interface
html HTMLDocument
xml XMLDocument
text XMLDocument mit einem einzelnen Wurzelelement <transformiix:result> und dem Text als Kindknoten

Beispiele

Verwendung von transformToDocument()

Dieses Beispiel zeigt, wie transformToDocument() verwendet wird, um ein XML-Dokument mithilfe von XSLT zu transformieren, was eine neue XML-Dokumentstruktur ergibt.

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;

Ergebnis

Spezifikationen

Specification
DOM
# dom-xsltprocessor-transformtodocument

Browser-Kompatibilität

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
transformToDocument

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
See implementation notes.

Siehe auch