0

たとえば、これをどのように変更しますか。

<chapter name="Chapter 1">
  <chapter name="Chapter 1.1">
    <chapter name="Chapter 1.1.1">
      <chapter name="Chapter 1.1.1.1"/>
    </chapter>
    <chapter name="Chapter 1.1.2"/>
  </chapter>
  <chapter name="Chapter 1.2"/>
</chapter>

これに:

<h1>Chapter 1</h1>
<h2>Chapter 1.1</h2>
<h3>Chapter 1.1.1</h3>
<h4>Chapter 1.1.1.1</h4>
<h3>Chapter 1.1.2</h3>
<h2>Chapter 1.2</h2>

ありがとう!

4

1 に答える 1

3

それを行う方法はいくつかの可能性があります。見出しのレベルを示すものによって異なります (@name属性の数値? 要素の深さchapter?)。

chapter要素の深さだと思います。入力xmlの場合

<?xml version="1.0" encoding="UTF-8"?>
<chapter name="Chapter 1">
    <chapter name="Chapter 1.1">
        <chapter name="Chapter 1.1.1">
            <chapter name="Chapter 1.1.1.1"/>
        </chapter>
        <chapter name="Chapter 1.1.2"/>
    </chapter>
    <chapter name="Chapter 1.2"/>
</chapter>

連続呼び出しでパラメーターが増加するテンプレートを利用できますapply-templates

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

    <xsl:template match="/">
        <html>
            <head>
                <title>xxx</title>
            </head>
            <body>
                <xsl:apply-templates select="chapter" />
            </body>
        </html>
    </xsl:template>

    <xsl:template match="chapter">
        <xsl:param name="level" select="1" />

        <xsl:element name="h{$level}">
            <xsl:value-of select="@name" />
        </xsl:element>

        <xsl:apply-templates select="chapter">
            <!-- Increase level of heading -->
            <xsl:with-param name="level" select="$level+1" />
        </xsl:apply-templates>

    </xsl:template>

</xsl:stylesheet>

次の出力を生成します

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>xxx</title>
    </head>
    <body>
        <h1>Chapter 1</h1>
        <h2>Chapter 1.1</h2>
        <h3>Chapter 1.1.1</h3>
        <h4>Chapter 1.1.1.1</h4>
        <h3>Chapter 1.1.2</h3>
        <h2>Chapter 1.2</h2>
    </body>
</html>

編集:別のアイデアは、このような「親」の章要素の数を数えることができます

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

    <xsl:template match="/">
        <html>
            <head>
                <title>xxx</title>
            </head>
            <body>
                <xsl:apply-templates select="//chapter" />
            </body>
        </html>
    </xsl:template>

    <xsl:template match="chapter">
        <xsl:variable name="level" select="count(ancestor-or-self::chapter)" />
        <xsl:element name="h{$level}">
            <xsl:value-of select="@name" />
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>
于 2013-09-03T07:13:37.183 に答える