3

私は単純な xsl スタイルを xml ドキュメントに適用しようとしています:

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

  <xsl:template match="/">
    <html>
      <body>

        <xsl:for-each select="//title">
          <h1><xsl:value-of select="."/></h1>
        </xsl:for-each>

      </body>
    </html>
  </xsl:template>

</xsl:stylesheet>

残念ながら、これは単に他のすべてのタグを無視し、それらとその内容を出力から削除するだけのようで、h1s に変換されたタイトルだけが残っています。私ができるようにしたいのは、タグの一部だけを置き換えながら、ドキュメントの構造を維持することです。

たとえば、このドキュメントがある場合:

<section>
  <title>Hello world</title>
  <p>Hello!</p>
</section>

私はこれを得ることができました:

<section>
  <h1>Hello world</h1>
  <p>Hello!</p>
</section>

XSLT マニュアルのどこから調べればよいのかよくわかりません。

4

2 に答える 2

7

OR Mapper が言うように、これに対する解決策は、ID テンプレートをトランスフォームに追加し、必要な部分をオーバーライドすることです。これは完全な解決策です:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>

  <!-- Identity template -->
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/">
    <html>
      <body>
        <xsl:apply-templates select="@* | node()" />
      </body>
    </html>
  </xsl:template>

  <xsl:template match="title">
    <h1>
      <xsl:apply-templates select="@* |node()" />
    </h1>
  </xsl:template>
</xsl:stylesheet>

サンプル入力で実行すると、次が生成されます。

<html>
  <body>
    <section>
      <h1>Hello world</h1>
      <p>Hello!</p>
    </section>
  </body>
</html>

元の XML を保持して を置き換えたいだけの場合は<title>、中間<xsl:template>を削除するだけで結果が得られます。

<section>
  <h1>Hello world</h1>
  <p>Hello!</p>
</section>
于 2013-02-02T15:18:25.507 に答える
2

<title>要素だけを置き換えたい。ただし、XSLT では、/ドキュメントのルート要素 ( ) のテンプレートを定義し、ルート要素全体をテンプレートのコンテンツに置き換えます。

実際にやりたいことは、ソース ドキュメントから基本的にすべてをコピーするための恒等変換テンプレート (google this、XSLT では重要な概念です) を定義し、次のように、要素のみに一致<title>して新しいコードに置き換えるテンプレートを定義することです。 :

<xsl:template match="title">
    <h1><xsl:value-of select="."/></h1>
</xsl:template>
于 2013-02-02T13:48:00.973 に答える