2015-06-22 107 views
-1

的計數我有屬性的XML文檔屬於機構:有關排序基於子元素

<agency name="Century 42" num="Century42" mail="[email protected]"/> 
<property agency="Century42" ....> 
... 

我想打印所有機構的信息。這些機構應該按照他們擁有的物業數量進行排序。

我試過,但它不工作:

<xsl:apply-templates select="immo/agency"> 
<xsl:sort select="count(//property[@[email protected]])"/> 
</xsl:apply-templates> 

計數無效。

+0

請(1)向我們展示了XML輸入的**完成**例如,和(2)表示XSLT 1.0或2.0。 –

回答

0

您可以使用一個鍵來計算排序指令中的屬性。含有樣式表中的以下內容:

<xsl:key name="p" match="property" use="@agency"/> 

<xsl:template match="/immo"> 
    <result> 
     <xsl:for-each select="agency"> 
     <xsl:sort select="count(key('p', @name))"/> 
     <res id="{ @name }" count="{ count(key('p', @name)) }"/> 
    </xsl:for-each> 
    </result> 
</xsl:template> 

當施加到以下輸入:

<immo> 
    <agency name="a"/> 
    <agency name="b"/> 
    <agency name="c"/> 
    <property agency="a"/> 
    <property agency="a"/> 
    <property agency="a"/> 
    <property agency="b"/> 
    <property agency="b"/> 
    <property agency="b"/> 
    <property agency="b"/> 
    <property agency="c"/> 
</immo> 

產生以下輸出:

<result> 
    <res id="c" count="1"/> 
    <res id="a" count="3"/> 
    <res id="b" count="4"/> 
</result> 

如果要以相反的順序,對xsl:sort使用order="descending"

編輯:如果property/@agency可以有幾個機構的數字,由空格分開,下面的解決方案的工作,而不是(不使用鍵,雖然,再次選擇,每家機構在文檔中的所有屬性):

<xsl:template match="/immo"> 
    <result> 
     <xsl:for-each select="agency"> 
     <xsl:sort select="count(//property[tokenize(@agency, '\s+') = current()/@name])"/> 
     <res id="{ @name }"/> 
    </xsl:for-each> 
    </result> 
</xsl:template> 
+0

如果一個房產可能屬於多個機構(使用idrefs)會怎麼樣?如何在這種情況下對機構進行分類? – user5036207

+0

我編輯了我的答案。 –

0

僅供參考,我接到一個簡單的回答我的問題

<xsl:apply-templates select="immo/agency"> 
<xsl:sort select="count(//property[contains(@agency, current()/@num)])" order="descending"/> 
</xsl:apply-templates> 
+0

小心'contains'。是不可能有一個機構代碼是另一個的子字符串?例如。 'century21'和'century21.branch12'。或「世紀」和「世紀21」。 –