2014-09-03 53 views
-1

我是XSLT的新手,我需要帮助将两个不同的XML文档合并为一个。使用XSLT合并两个diff XMLS(1.0)

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将被认为是在该上下文中外部。我需要为每个客户添加相应的产品。我怎样才能做到这一点?

+0

请注明XSLT 1.0或2.0。 - 注意:“Ram”与“Ram”不同;你确定这就是你的数据看起来的样子吗? – 2014-09-03 09:28:20

+0

第二次看,它不可能,因为它不是格式良好。这个''不是XML。 – 2014-09-03 09:35:43

+0

嗨@ michael.hor257k,我已更新查询 – user3698644 2014-09-03 10:36:12

回答

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> 

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

+0

也许您应该对原始XML进行修改,为每个产品提供一个消费者ID(我猜这是真正唯一的),而不是消费者的名称,并对此ID进行转换。 – Kilazur 2014-09-03 10:56:34

+0

@Kilazur也许你应该解决这个问题? – 2014-09-03 11:16:01