2012-10-11 57 views
0

File1.xml如何使用xslt1.0合并两个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

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