1

したがって、基本的にXMLノードをループする関数が必要であり、条件がtrueの場合、その値を変数に追加します。ソーシャル投稿を集計しているので、フィードに含まれる各ソーシャル投稿の数を数える必要があります。これが私のXMLです:

 <feed>
   <channel>
     <sources>
       <source>
           <name>Facebook</name>
           <count>3</count>
       </source>
       <source>
           <name>Twitter</name>
           <count>2</count>
       </source>
       <source>
           <name>Twitter</name>
           <count>8</count>
        </source>
     </sources>
   </channel>
  </feed>

キャッチは同じソースが複数回表示される可能性があるため、それらを合計する必要があります。したがって、上記のXMLのTwitterカウントは10が必要になります。これが私が今のところいるところです:

<xsl:variable name="num_tw">
<xsl:for-each select="feed/channel/sources/source">
  <xsl:choose>
    <xsl:when test="name, 'twitter')">
      <xsl:value-of select="count"/>
    </xsl:when>
    <xsl:otherwise></xsl:otherwise>
  </xsl:choose>
</xsl:for-each>
</xsl:variable>

<xsl:variable name="num_fb">
<xsl:for-each select="feed/channel/sources/source">
  <xsl:choose>
    <xsl:when test="name, 'facebook')">
      <xsl:value-of select="count"/>
    </xsl:when>
    <xsl:otherwise></xsl:otherwise>
  </xsl:choose>
</xsl:for-each>
</xsl:variable>

Twitterフィードが2つある場合、数字を並べて「10」ではなく「28」を出力するため、これは機能しません。どんな助けでも大歓迎です!

4

1 に答える 1

4

ここでxsl:for-eachを使用してノードを反復処理する必要はありません。代わりに、 sum演算子を使用できます。たとえば、num_tw変数は次のように書き直すことができます。

<xsl:variable name="num_tw" select="sum(feed/channel/sources/source[name='Twitter']/count)"/>

ただし、ここでフィード名を本当にハードコーディングしますか?これは実際には「グループ化」の問題であり、XSLT 1.0では、MuencianGroupingと呼ばれる手法を使用して解決します。あなたの場合、ソース要素をそれらの名前要素でグループ化したいので、次のようにキーを定義します。

<xsl:key name="source" match="source" use="name" />

次に、すべてのソース要素を確認し、指定された名前要素のグループの最初の要素を選択します。

<xsl:apply-templates 
   select="feed/channel/sources/source[generate-id() = generate-id(key('source', name)[1])]" />

次に、これに一致するテンプレート内で、次のようにカウントを合計できます。

<xsl:value-of select="sum(key('source', name)/count)" />

これが完全なXSLTです

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:key name="source" match="source" use="name" />

    <xsl:template match="/">
    <xsl:apply-templates select="feed/channel/sources/source[generate-id() = generate-id(key('source', name)[1])]" />

    </xsl:template>

    <xsl:template match="source">
        <source>
            <xsl:copy-of select="name" />
            <count><xsl:value-of select="sum(key('source', name)/count)" /></count>
        </source>
    </xsl:template>
</xsl:stylesheet>

XMLに適用すると、次のように出力されます。

<source>
   <name>Facebook</name>
   <count>3</count>
</source>
<source>
   <name>Twitter</name>
   <count>10</count>
</source>

「Facebook」のように特定のフィードの数を本当に知りたい場合でも、ここでキーを使用することが望ましいことに注意してください。例えば:

<xsl:variable name="num_fb" select="sum(key('source', 'Facebook')/count)"/>
于 2013-02-11T20:17:13.510 に答える