使用XSLT(1.0)合并两个不同的XMLS

时间:2014-09-03 09:23:59

标签: xslt

我是XSLT的新手,我需要帮助将两个不同的XML文档合并为一个。

XML1.xml

<customers>
    <customer>
        <Person name="Ram" Id="101"/>
        <address>flat 4</address>
    </customer>
    <customer>
        <Person name="Raghav" Id="102"/>
        <address>flat 9</address>
    </customer>
</customers>

XML2.xml

<Products>
    <Product>
        <name>Onida Tv</name>
        <consumer>Ram</consumer>
    </Product>
    <Product>
        <name>washing machine</name>
        <consumer>Ram</consumer>
    </Product>
    <Product>
        <name>Water purifier</name>
        <consumer>Raghav</consumer>
    </Product>
    <Product>
        <name>iPhone</name>
        <consumer>Raghav</consumer>
    </Products>
</Products>

所需的XML输出:

<customers>
    <customer>
        <Person name="Ram" Id="101"/>
        <address>flat 4</address>
        <products>
            <name>washing machine</name>
            <name>Onida TV</name>
        </products>
    </customer>
    <customer>
        <Person name="Raghav" Id="102"/>
        <address>flat 9</address>
        <products>
            <name>iPhone</name>
            <name>Water purifier</name>
        </products>
    </customer>
</customers>

在此上下文中,第二个XML将被视为外部XML。我需要向每个客户追加相应的产品。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

以这种方式尝试:

XSLT 1.0

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.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:variable name="lookup-document" select="document('XML2.xml')" />
<xsl:key name="product-by-consumer" match="Product" use="consumer" />

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

<xsl:template match="customer">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <xsl:variable name="name" select="Person/@name" />
        <products>
            <!--  switch context to the other document in order to use key -->
            <xsl:for-each select="$lookup-document">
                <xsl:copy-of select="key('product-by-consumer', $name)/name"/>
            </xsl:for-each> 
        </products>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

请注意,这假设客户名称是唯一的。

相关问题