如何使用 xslt1.0 合并两个 xml 文件



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>

文件2.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>

你需要使用 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>

相关内容

  • 没有找到相关文章

最新更新