2017-09-24 60 views
0

從類似:XSLT - 計數每個元件的位置取決於屬性值

<Play> 
    <Character key="Horatio">[...]</Character> 
    <Character key="Hamlet">[...]</Character> 
    <Character key="Ghost">[...]</Character> 
    <Character key="Hamlet">[...]</Character> 
    <Character key="Polonius">[...]</Character> 
    <Character key="Hamlet">[...]</Character> 
    <Character key="Hamlet">[...]</Character> 
    <Character key="Queen">[...]</Character> 
    <Character key="Horatio">[...]</Character> 
</Play> 

我想輸出的副本,將通過作爲附加屬性的那些共享相同的中的每個元件的位置@關鍵,如:

<Play> 
    <Character key="Horatio" token="1">[...]</Character> 
    <Character key="Hamlet" token="1">[...]</Character> 
    <Character key="Ghost" token="1">[...]</Character> 
    <Character key="Hamlet" token="2">[...]</Character> 
    <Character key="Polonius" token="1">[...]</Character> 
    <Character key="Hamlet" token="3">[...]</Character> 
    <Character key="Hamlet" token="4">[...]</Character> 
    <Character key="Queen" token="1">[...]</Character> 
    <Character key="Horatio" token="2">[...]</Character> 
</Play> 

由於這是一種後續行動較早的排序問題(XSLT – Pass attributes to create parent elements, then order filtered results),我試圖用添C'S答案,我的基礎,並使用xsl:結合數與它,但我沒有成功。

非常感謝!

+2

*我試着使用提姆C的答案* ...請張貼這樣的嘗試。 – Parfait

回答

0

簡單的解決方案是按鍵對字符進行分組,並使用它們在每個組內的位置。

如果您需要保留原來的順序(或創造一些其他性質不同的順序),嘗試了不同的方法:

XSLT 2.0

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

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

<xsl:key name="grp" match="Character" use="@key" /> 

<xsl:template match="Character"> 
    <Character key="{@key}" token="{index-of(key('grp', @key)/generate-id(), generate-id())}"> 
     <xsl:apply-templates/> 
    </Character> 
</xsl:template> 

</xsl:stylesheet>