一个 XML 文件可以有 1000 - 6000 个表单;两个 XML 文件可能有 1 到 100 个或更多。我想用文件二替换文件一中的任何相同表格。如果它存在于文件 2 中但不存在于文件 1 中,我想将它添加到文件 1 中。文件合并后,我想针对我的 XSLT 运行它。我使用的是 2.0 样式表和 Saxon 解析器。
文件 1:
<Forms><br/> <Form name="fred" date="10/01/2008"/><br/> <Form name="barney" date="12/31/2009"/><br/> <Form name="wilma" date="12/31/2010"/><br/> </Forms>
文件 2:
<Forms><br/> <Form name="barney" date="01/31/2010"/><br/> <Form name="betty" date="6/31/2009"/><br/> </Forms>
合并后的文件应该是这样的:
<Forms><br/> <Form name="fred" date="10/01/2008"/><br/> <Form name="barney" date="01/31/2010"/><br/> <Form name="wilma" date="12/31/2010"/><br/> <Form name="betty" date="6/31/2009"/><br/> </Forms>
最佳答案
如果维护文档顺序不是优先事项:
<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>
关于xml - 使用 XSLT 合并两个 XML 源文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2192627/