【问题标题】:Merging two XML source documents with XSLT使用 XSLT 合并两个 XML 源文档
【发布时间】:2010-02-03 14:32:24
【问题描述】:

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

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

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-10-02
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多