2010-02-03 87 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>