2010-02-03 85 views
2

XML文件可以包含1000-6000個表單; XML文件兩個可以有一個到100個或更多。我想用文件2替換文件1中的任何相同的表單。如果它存在於文件2中但不在文件1中,我想將其添加到文件1.合併文件後,我想針對我的XSLT運行它。我正在使用2.0樣式表和撒克遜分析器。將兩個XML源文檔與XSLT合併

文件1:

<Forms>
<Form name="fred" date="10/01/2008"/>
<Form name="barney" date="12/31/2009"/>
<Form name="wilma" date="12/31/2010"/>
</Forms>

文件2:

<Forms>
<Form name="barney" date="01/31/2010"/>
<Form name="betty" date="6/31/2009"/>
</Forms>

合併後的文件應該是這樣:

<Forms>
<Form name="fred" date="10/01/2008"/>
<Form name="barney" date="01/31/2010"/>
<Form name="wilma" date="12/31/2010"/>
<Form name="betty" date="6/31/2009"/>
</Forms>

回答

7

如果維持文檔順序是不是一個優先事項:

<xsl:variable name="forms1" select="document('forms1.xml')/Forms/Form" /> 
<xsl:variable name="forms2" select="document('forms2.xml')/Forms/Form" /> 

<xsl:variable name="merged" select=" 
    $forms1[not(@name = $forms2/@name)] | $forms2 
" /> 

<xsl:template match="/"> 
    <xsl:apply-templates select="$merged" /> 
</xsl:template> 

<xsl:template match="Form"> 
    <!-- for the sake of the example; you can use a more specialized template --> 
    <xsl:copy-of select="." /> 
</xsl:template> 

如果維持文檔順序是什麼原因...優先

<xsl:template match="/"> 
    <!-- check values of file 1 sequentially, and replace them if needed --> 
    <xsl:for-each select="$forms1"> 
    <xsl:variable name="this" select="." /> 
    <xsl:variable name="newer" select="$forms2[@name = $this/@name]" /> 
    <xsl:choose> 
     <xsl:when test="$newer"> 
     <xsl:apply-templates select="$newer" /> 
     </xsl:when> 
     <xsl:otherwise> 
     <xsl:apply-templates select="$this" /> 
     </xsl:otherwise> 
    </xsl:choose> 
    </xsl:for-each> 
    <!-- append any values from file 2 that are not in file 1 --> 
    <xsl:apply-templates select="$forms2[not(@name = $forms1/@name)]" /> 
</xsl:template>