2015-04-17 52 views
2

兩個XML文件我有兩個XML文件:比較使用XSLT

文件 「一」:

<?xml version="1.0"?> 
<catalog> 
    <cd>d</cd> 
    <cd>e</cd> 
    <cd>f</cd> 
    <cd>c</cd> 
</catalog> 

文件 「B」:

<?xml version="1.0"?> 
<catalog> 
    <cd>a</cd> 
    <cd>b</cd> 
    <cd>c</cd> 
</catalog> 

我想比較的文件b反對文件a並獲取那些只存在於文件b中的記錄。

即期望的輸出是:

<?xml version="1.0"?> 
<catalog> 
    <cd>a</cd> 
    <cd>b</cd> 
</catalog> 
+0

我是相當新的這一點。 – sidGupta

+0

我試圖嵌套一個「for-each」循環,但問題的產生是因爲我們無法改變一次賦值變量的值 – sidGupta

+0

請指明XSLT 1.0或2.0。 –

回答

2

如果您可以使用XSLT 2.0,那麼可以非常簡單地(有效地)通過使用。假設你正在處理的 「B」 文件:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/> 

<xsl:key name="cd" match="cd" use="." /> 

<xsl:template match="/catalog"> 
    <xsl:copy> 
     <xsl:copy-of select="cd[not(key('cd', ., document('a.xml')))]"/> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 
1

一個簡單的解決方案可以如下:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> 
    <xsl:param name="compareWith" select="'a.xml'"/> 

    <xsl:template match="*"> 
     <xsl:copy> 
      <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="cd"> 
     <xsl:if test="not(document($compareWith)//cd = .)"> 
      <xsl:copy> 
       <xsl:apply-templates/> 
      </xsl:copy> 
     </xsl:if> 
    </xsl:template> 
</xsl:stylesheet> 

主要的一點是,我們檢查實際cd內容是否不存在文檔中的相應($compareWith