如何使用 xslt1.0 合并两个 xml 文件? [英] How to merge two xml file using xslt1.0?

查看:41
本文介绍了如何使用 xslt1.0 合并两个 xml 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件 1.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 需要像下面这样的输出

need output like below using 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() 函数,如下所示:

You need to use the document() function, like so:

<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>

这篇关于如何使用 xslt1.0 合并两个 xml 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆