使用 XSLT 合并两个 XML 源文档 [英] Merging two XML source documents with XSLT

查看:36
本文介绍了使用 XSLT 合并两个 XML 源文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XML 文件可以有 1000 - 6000 个表单;XML 文件两个可能有 1 到 100 个或更多.我想用文件二替换文件一中的任何相同形式.如果它存在于文件 2 但不在文件 1 中,我想将它添加到文件 1.合并文件后,我想针对我的 XSLT 运行它.我使用的是 2.0 样式表和 Saxon 解析器.

XML file one could have 1000 - 6000 forms; XML file two could have one to 100 or more. I want to replace any identical form in file one with file two. If it exists in file 2 but not in file one I want to add it to file 1. After the files are merged I want to run it against my XSLT. I am using a 2.0 stylesheet and a Saxon parser.

文件 1:

<代码><表单>
<表单名称=fred"日期=10/01/2008"/>
<表格名称=barney"日期=12/31/2009"/>
<表单名称="wilma" date="12/31/2010"/>
</表单>

文件 2:

<代码><表单>
<表格名称=barney"日期=01/31/2010"/>
<表单名称="betty" 日期="6/31/2009"/>
</表单>

合并后的文件应如下所示:

Merged file should look like:

<代码><表单>
<表单名称=fred"日期=10/01/2008"/>
<表格名称=barney"日期=01/31/2010"/>
<表单名称="wilma" date="12/31/2010"/>
<表单名称="betty" 日期="6/31/2009"/>
</表单>

推荐答案

如果维护文档顺序不是优先事项:

If maintaining document order is not a priority:

<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>

如果无论出于何种原因,保持文档顺序是一个优先事项......

If maintaining document order is a priority for whatever reason…

<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>

这篇关于使用 XSLT 合并两个 XML 源文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆