我有一個訂單行列表,每個產品都在它們上面。這些產品可能會形成一個自我引用的層次結構。我需要以這樣一種方式排序:所有沒有父母或父母在訂單中缺失的產品位於頂部,其次是子女。最終結果中,沒有一個孩子可能超過其父母。如何訂購自引用xml
那麼,如何可以訂購以下XML:
<order>
<line><product code="3" parent="1"/></line>
<line><product code="2" parent="1"/></line>
<line><product code="6" parent="X"/></line>
<line><product code="1" /></line>
<line><product code="4" parent="2"/></line>
</order>
進入這個:
<order>
<line><product code="6" parent="X"/></line>
<line><product code="1" /></line>
<line><product code="2" parent="1"/></line>
<line><product code="3" parent="1"/></line>
<line><product code="4" parent="2"/></line>
</order>
注意,特定等級內的順序並不重要,只要孩子節點如下的它是父母之後的一點。
我有一個工程層次的解決方案不超過預定深度:
<order>
<xsl:variable name="level-0"
select="/order/line[ not(product/@parent=../line/product/@code) ]"/>
<xsl:for-each select="$level-0">
<xsl:copy-of select="."/>
</xsl:for-each>
<xsl:variable name="level-1"
select="/order/line[ product/@parent=$level-0/product/@code ]"/>
<xsl:for-each select="$level-1">
<xsl:copy-of select="."/>
</xsl:for-each>
<xsl:variable name="level-2"
select="/order/line[ product/@parent=$level-1/product/@code ]"/>
<xsl:for-each select="$level-2">
<xsl:copy-of select="."/>
</xsl:for-each>
</order>
以上示例XSLT將爲層次工作,3個級別的最大深度,並很容易擴展到更多,但我怎麼能概括這一點,並讓xslt正確排序任意級別的深度?
「*所有沒有父母或父母在訂單中缺失的產品都位於頂部,其次是子女。*」您是否想讓父母立即跟隨**,孩子,或一起列出同一代的所有項目。 –