使用 XSLT 轉換 XML

適用於:所有 API 管理 層

xsl-transform 原則會將 XSL 轉換套用至要求或回應本文中的 XML。

注意

請依照原則陳述式中提供的順序,來設定原則的元素和子元素。 深入了解如何設定或編輯 APIM 原則

原則陳述式

<xsl-transform>
    <parameter parameter-name="...">...</parameter>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:.../>
        <xsl:.../>
    </xsl:stylesheet>
  </xsl-transform>

元素

名稱 描述 必要
parameter 用於定義轉換中使用的變數 No
xsl:stylesheet 根樣式表元素。 遵循標準 XSLT 規格 (英文) 內定義的所有元素和屬性。 Yes

使用方式

使用注意事項

  • 此原則只能在原則區段中使用一次。
  • 此原則目前支援 XSLT 1.0 版。

範例

轉換要求本文

<inbound>
    <base />
    <xsl-transform>
        <parameter name="User-Agent">@(context.Request.Headers.GetValueOrDefault("User-Agent","non-specified"))</parameter>
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <xsl:output method="xml" indent="yes" />
            <xsl:param name="User-Agent" />
            <xsl:template match="* | @* | node()">
                <xsl:copy>
                    <xsl:if test="self::* and not(parent::*)">
                        <xsl:attribute name="User-Agent">
                            <xsl:value-of select="$User-Agent" />
                        </xsl:attribute>
                    </xsl:if>
                    <xsl:apply-templates select="* | @* | node()" />
                </xsl:copy>
            </xsl:template>
        </xsl:stylesheet>
      </xsl-transform>
</inbound>

轉換回應本文

<policies>
  <inbound>
      <base />
  </inbound>
  <outbound>
      <base />
      <xsl-transform>
          <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <xsl:output omit-xml-declaration="yes" method="xml" indent="yes" />
            <!-- Copy all nodes directly-->
            <xsl:template match="node()| @*|*">
                <xsl:copy>
                    <xsl:apply-templates select="@* | node()|*" />
                </xsl:copy>
            </xsl:template>
          </xsl:stylesheet>
    </xsl-transform>
  </outbound>
</policies>

如需使用原則的詳細資訊,請參閱: