如何将两个XML文档与XSLT合并(可以是XSLT 2.0)?

时间:2015-07-03 23:46:59

标签: xml xslt merge

我有两个文件,其中包含单独收集的相关信息。当每个处理器完成以相同格式收集xml数据时,如何使用XSLT合并两个xml文件?

例如:

AllSets_Names.xml

<Sets>
    <Set id="1">
        <SetName>World Champ Decks 1999</SetName>
    </Set>
    <Set id="2">
        <SetName>World Champ Decks 1999</SetName>
    </Set>
    <Set id="3">
        <SetName>World Champ Decks 1999</SetName>
    </Set>
    <Set id="4">
        <SetName>World Champ Decks 1999</SetName>
    </Set>
    <Set id="5">
        <SetName>World Champ Decks 1999</SetName>
    </Set>
</Sets>

AllSets_ShortNames.xml

<Sets>
    <Set id="1">
        <SetShortName>W99</SetShortName>
    </Set>
    <Set id="2">
        <SetShortName>W00</SetShortName>
    </Set>
    <Set id="3">
        <SetShortName/>
    </Set>
    <Set id="4">
        <SetShortName>WD2</SetShortName>
    </Set>
    <Set id="5">
        <SetShortName>WD3</SetShortName>
    </Set>
</Sets>

所需的输出:AllSets_NamesAndShortNames.xml

<Sets>
    <Set id="1">
        <SetName>World Champ Decks 1999</SetName>
        <SetShortName>W99</SetShortName>
    </Set>
    <Set id="2">
        <SetName>World Champ Decks 1999</SetName>
        <SetShortName>W00</SetShortName>
    </Set>
    <Set id="3">
        <SetName>World Champ Decks 1999</SetName>
        <SetShortName/>
    </Set>
    <Set id="4">
        <SetName>World Champ Decks 1999</SetName>
        <SetShortName>WD2</SetShortName>
    </Set>
    <Set id="5">
        <SetName>World Champ Decks 1999</SetName>
        <SetShortName>WD3</SetShortName>
    </Set>
</Sets>

2 个答案:

答案 0 :(得分:2)

执行此操作的好方法是使用分组:

<xsl:template name="main">
  <Sets>
    <xsl:for-each-group
      select="document(('Names.xml','ShortNames.xml'))/Sets/Set"
      group-by="@id">
      <Set>
        <xsl:copy-of select="current-group()/(@*, *)"/>
      </Set>
   </xsl:for-each-group>
 </Sets>
</xsl:template>

答案 1 :(得分:1)

你可以这样做:

XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="short-names-path" select="'AllSets_ShortNames.xml'"/>
<xsl:key name="set-by-id" match="Set" use="@id" />

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Set">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <xsl:copy-of select="key('set-by-id', @id, document($short-names-path))/SetShortName"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

这假设您正在处理AllSets_Names.xml文档并将路径作为参数传递给AllSets_ShortNames.xml