兩個例子。這個樣式表使用CLASIC全遞歸:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="kNutChildByBisName" match="nutritionalValue/*"
use="../../@name"/>
<xsl:key name="kElemByPrecedingName" match="biscuit/*[not(self::name)]"
use="preceding-sibling::name[1]"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="name" mode="group">
<bisquit>
<xsl:apply-templates select=".|key('kNutChildByBisName',.)|
key('kElemByPrecedingName',.)"/>
</bisquit>
</xsl:template>
<xsl:template match="biscuit">
<xsl:apply-templates mode="group"/>
</xsl:template>
<xsl:template match="biscuitInfo"/>
<xsl:template match="node()" mode="group"/>
</xsl:stylesheet>
而這個樣式表使用細粒度遍歷:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:key name="kNutByBisName" match="nutritionalValue"
use="../@name"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()[1]|@*"/>
</xsl:copy>
<xsl:apply-templates select="following-sibling::node()[1]"/>
</xsl:template>
<xsl:template match="biscuitInfo"/>
<xsl:template match="biscuit">
<xsl:apply-templates select="node()[1]|following-sibling::node()[1]"/>
</xsl:template>
<xsl:template match="name[1]" name="group">
<bisquit>
<xsl:call-template name="identity"/>
<xsl:apply-templates select="key('kNutByBisName',.)/node()[1]"/>
</bisquit>
<xsl:apply-templates select="following-sibling::name[1]" mode="group"/>
</xsl:template>
<xsl:template match="name"/>
<xsl:template match="name" mode="group">
<xsl:call-template name="group"/>
</xsl:template>
</xsl:stylesheet>
有了這個輸入:
<root>
<biscuit>
<name>Hobnobs</name>
<price>1.49</price>
<name>Digestives</name>
<price>89.00</price>
</biscuit>
<biscuitInfo name="Hobnobs">
<nutritionalValue>
<fat>6 grams</fat>
<sugar>lots</sugar>
</nutritionalValue>
</biscuitInfo>
<biscuitInfo name="Digestives">
<nutritionalValue>
<fat>3 grams</fat>
<sugar>5 grams</sugar>
</nutritionalValue>
</biscuitInfo>
</root>
兩個輸出:
<root>
<bisquit>
<name>Hobnobs</name>
<price>1.49</price>
<fat>6 grams</fat>
<sugar>lots</sugar>
</bisquit>
<bisquit>
<name>Digestives</name>
<price>89.00</price>
<fat>3 grams</fat>
<sugar>5 grams</sugar>
</bisquit>
</root>
注意:您正在執行兩項任務:分組和交叉引用。
編輯:在組中只有name
的情況下更好的細粒度遍歷。
是否需要在xslt中創建一個變量來表示循環當前所關注的值?或者我可以直接在Xpath查詢中使用它? – jdoig 2010-12-13 10:35:49
我認爲這兩個選項都可以有效。創建一個變量會給你更短的表達式,但我認爲你可以在xpath查詢中直接使用你的值。 – 2010-12-13 10:49:01
太好了,謝謝。我不認爲你有什麼好的鏈接顯示這樣的技術嗎?只是爲了救我掙扎。乾杯。 – jdoig 2010-12-13 10:52:55