首页 > 解决方案 > 如果元素内容相同,XSLT 合并两个 XML 文件

问题描述

我需要以特定方式合并两个 XML 文件。

XML 文件 1

<csv_data>
<row>
    <important_id>AAAAAAAAAAAAAAAA</important_id>
    <importantstuff>very important</importantstuff>
    <alotmore>stuff</alotmore>
</row>
<row>
    <important_id>BBBBBBBBBBBBBBBB</important_id>
    <importantstuff>very important</importantstuff>
    <alotmore>stuff</alotmore>
</row>

XML 文件 2

<csv_data2>
<row1>
    <some_id>213421342134</some_id>
    <important_id>AAAAAAAAAAAAAAAA</important_id>
    <another_id>125135345345</another_id>
    <importantstuffhere>very important stuff here</importantstuffhere>
    <alotmoreandmore>stuff</alotmoreandmore>
</row1>
<row2>
    <some_id>3452345</some_id>
    <important_id>AAAAAAAAAAAAAAAA</important_id>
    <another_id>234234</another_id>
    <importantstuffhere>very important stuff here2</importantstuffhere>
    <alotmoreandmore>stuff2</alotmoreandmore>
</row2>

合并的 XML 文件

<csv_data>
<row>
    <important_id>AAAAAAAAAAAAAAAA</important_id> (from XML-file 1)
    <importantstuff>very important</importantstuff> (from XML-file 1)
    <alotmore>stuff</alotmore> (from XML-file 1)
    <importantstuffhere>very important stuff here</importantstuffhere> (from XML-file 2 row1)
    <importantstuffhere>very important stuff here2</importantstuffhere> (from XML-file 2 row2)
    <importantstuffhere>very important stuff here3</importantstuffhere> (from XML-file 2 row3)
</row>
<row>
    <important_id>BBBBBBBBBBBBBBBB</important_id> (from XML-file 1)
    <importantstuff>very important</importantstuff> (from XML-file 1)
    <alotmore>stuff</alotmore> (from XML-file 1)
    <importantstuffhere>very important stuff here</importantstuffhere> (from XML-file 2 row20)
    <importantstuffhere>very important stuff here2</importantstuffhere> (from XML-file 2 row21)
</row>

XML-file 1 只有 1 次,XML-file 2 可以有相同的 ID 几次 tousend。现在我需要来自与 XML-File1 合并的同一 ID 的 XML-file2 的姐妹元素。我的意思有点清楚吗?

我需要先列出所有 ID 吗?我真的不知道从哪里开始。我只知道我需要 [...]apply-templates select="document('xml-file')[...].

标签: xmlxslt

解决方案


我想我找到了解决方案:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:strip-space elements="*"/>
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

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

<xsl:template match="row">
    <xsl:copy>
        <xsl:apply-templates/>
        <xsl:copy-of select="document('file2.xml')//row[important_id = current()/important_id]"/>
    </xsl:copy>
</xsl:template>

输出不是我想要的,但我想我可以从这里开始工作。


推荐阅读