如何使用xslt 1.0合并两个xml文件?

时间:2012-10-11 05:03:47

标签: xslt xslt-1.0

File1.xml

<?xml version="1.0" encoding="ISO-8859-1"?>  
<catalog>
  <data>
    <title>Title1</title>
    <description>Description1</description>
    <myid>1</myid>
  </data>    
  <data>
    <title>Title2</title>
    <description>Description2</description>
    <myid>2</myid>
  </data>
</catalog>

File2.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
  <data>
    <author>Author1</author>
    <date>12/34/5678</date>
    <myid>1</myid>
  </data>
  <data>
    <author>Author2</author>
    <date>87/65/4321</date>
    <myid>2</myid>
  </data>
</catalog>

使用xslt1.0需要输出如下

<catalog>
  <data>
    <title>Title1</title>
    <description>Description1</description>
    <myid>1</myid>
    <author>Author1</author>
    <date>12/34/5678</date>
  </data>    
  <data>
    <title>Title2</title>
    <description>Description2</description>
    <myid>2</myid>
    <author>Author2</author>
    <date>87/65/4321</date>
  </data>
</catalog>

1 个答案:

答案 0 :(得分:1)

您需要使用document()功能,如下所示:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="no"/>

  <xsl:template match="/">
    <catalog>
      <!-- Apply to all data elements in file 1 -->
      <xsl:apply-templates select="document('file1.xml')/catalog/data" />
    </catalog>
  </xsl:template>

  <xsl:template match="data">
    <data>
      <!--Use myid as a lookup-->
      <xsl:variable name="myId" select="myid/text()" />
      <!--copy all data child nodes from file1-->
      <xsl:copy-of select="@* | node()"/>
      <!--copy all data child nodes from file2, excluding myid as we already have it-->
      <xsl:copy-of select="document('file2.xml')/catalog/data[myid=$myId]/*[not(local-name()='myid')]"/>
    </data>
  </xsl:template>
</xsl:stylesheet>