2013-08-28 73 views
2

我有以下數據XSL - 如何比較2組節點?

<parent> 
    <child>APPLES</child> 
    <child>APPLES</child> 
    <child>APPLES</child> 
</parent> 
<parent> 
    <child>APPLES</child> 
    <child>BANANA</child> 
    <child>APPLES</child> 
</parent> 

有一個簡單的方法來比較的父節點?或者我將不得不在每個for-each中嵌套for-each,並使用position()手動測試每個孩子?

+0

你想要什麼輸出? –

+0

在我的數據中有30多個節點,我正在通過查看每個節點。我想知道當前父項的子節點何時與以前的父項不同。 E.G,它可以是X X X,然後是X X X,然後是Y X Y.我想知道這是什麼時候發生的。 –

回答

2

XSLT 2.0具有的功能http://www.w3.org/TR/2013/CR-xpath-functions-30-20130521/#func-deep-equal所以可以編寫一個模板

<xsl:template match="parent[deep-equal(., preceding-sibling::parent[1])]">...</xsl:template> 

處理那些parent元素等於其前面的同級parent

如果你想用XSLT 1.0做到這一點,然後你用純文本內容的子元素序列的簡單的情況下,它應該足以編寫模板

<xsl:template match="parent" mode="sig"> 
    <xsl:for-each select="*"> 
    <xsl:if test="position() &gt; 1">|</xsl:if> 
    <xsl:value-of select="."/> 
    </xsl:for-each> 
</xsl:template> 

,然後使用它,如下所示:

<xsl:template match="parent"> 
    <xsl:variable name="this-sig"> 
    <xsl:apply-templates select="." mode="sig"/> 
    </xsl:variable> 
    <xsl:variable name="pre-sig"> 
    <xsl:apply-templates select="preceding-sibling::parent[1]" mode="sig"/> 
    </xsl:variable> 
    <!-- now compare e.g. --> 
    <xsl:choose> 
    <xsl:when test="$this-sig = $pre-sig">...</xsl:when> 
    <xsl:otherwise>...</xsl:otherwise> 
    </xsl:choose> 
</xsl:template> 

對於更復雜的內容,你需要細化模板計算「簽名」串的實施,你可能想在網上搜索,我相信Dimitre Novatchev已經張貼在早期,類似的問題的解決方案。

+0

感謝您的回覆,但不幸的是我僅限於XSLT 1.0 –

+0

在這種情況下,您必須通過遞歸模板實現一個等價物,該模板將兩個節點作爲其參數進行比較。 XPath 2.0 deep-equal()的規範可能被證明是有用的。 –

+0

@DerekHo,我已經添加了一些關於如何與XSLT 1.0進行比較的建議。 –