簡體   English   中英

使用XSLT合並兩個XML源文檔

[英]Merging two XML source documents with XSLT

XML文件可以有1000-6000個表格; XML文件2可以具有1到100或更多。 我想用文件2替換文件1中的任何相同形式。 如果它存在於文件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>

如果維護文檔順序不是優先事項:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM