1

私は以下のxmlファイルとxslt変換を持っています:

    <?xml version="1.0" encoding="utf-8" ?>
    <?xml-stylesheet version="1.0" type="text/xml" href="pets.xsl" ?>
    <pets>
        <pet name="Jace" type="dog" />
        <pet name="Babson" type="" />
        <pet name="Oakley" type="cat" />
        <pet name="Tabby" type="dog" />
    </pets>

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:key name="pets-key" match="pet" use="type" />
    <xsl:template match="/" >
        <html>
            <head><title></title></head>
            <body>
                <xsl:for-each select="key('pets-key', '' )" >
                    <xsl:value-of select="@name" />
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

キー機能を使用して空でないタイプのペットをすべて選択するにはどうすればよいですか?

4

1 に答える 1

1

2 つの注意点:

  1. キー定義にエラーがあります。use="type" ではなく、use="@type" を使用する必要があります。
  2. タイプが空ではないすべてのペットを選択し、引き続き key() 関数を使用するには、セットの違いが必要です。XPATH 1.0 での設定の違いの一般的なレシピは...

    $node-set1[count(. | $node-set2) != count($node-set2)]

全体として、key() を使用し、型が空ではないすべてのペットをリストするための、正しいが非効率な XSLT 1.0 スタイルシートは...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="html" indent="yes" />
<xsl:strip-space elements="*" />

<xsl:key name="kPets" match="pet" use="@type" />

<xsl:template match="/" >
  <html>
    <head><title>Pets with a type</title></head>
    <body>   
      <ul>
        <xsl:for-each select="*/pet[count(. | key('kPets', '' )) != count(key('kPets', '' ))]" >
          <li><xsl:value-of select="@name" /></li>
        </xsl:for-each>
      </ul>
    </body>
   </html>
</xsl:template>

</xsl:stylesheet>

これにより、出力が得られます...

<html>
  <head>
    <META http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Pets with a type</title>
  </head>
  <body>
    <ul>
      <li>Jace</li>
      <li>Oakley</li>
      <li>Tabby</li>
    </ul>
  </body>
</html>

そうは言っても、この質問は、キーを使用する上での適切な練習問題としては実際には当てはまりません。実生活で、この結果を達成したい場合、より優れた、より効率的な XSLT 1.0 ソリューションは...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="html" indent="yes" />
<xsl:strip-space elements="*" />

<xsl:key name="kPets" match="pet" use="@type" />

<xsl:template match="/*" >
  <html>
    <head><title>Pets with a type</title></head>
    <body>   
      <ul>
        <xsl:apply-templates />
      </ul>
    </body>
   </html>
</xsl:template>

<xsl:template match="pet[@type != .]">
  <li><xsl:value-of select="@name" /></li>
</xsl:template>  

</xsl:stylesheet>
于 2012-09-09T08:20:06.347 に答える