2013-01-03 45 views
-2

我有以下的XSL腳本,它可以通過一個字段連接兩個XML文件到一個文件:XSLT:加盟的XML文件任意數量到一個單一的XML

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:strip-space elements="*"/> 
    <xsl:output method="xml" indent="yes" /> 

    <xsl:key name="trans" match="Transaction" use="id" /> 

    <!-- Identity template to copy everything we don't specifically override --> 
    <xsl:template match="@*|node()"> 
    <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy> 
    </xsl:template> 

    <!-- override for Mail elements --> 
    <xsl:template match="Mail"> 
    <xsl:copy> 
     <!-- copy all children as normal --> 
     <xsl:apply-templates select="@*|node()" /> 
     <xsl:variable name="myId" select="id" /> 
     <Transaction_data> 
     <xsl:for-each select="document('transactions.xml')"> 
      <!-- process all transactions with the right ID --> 
      <xsl:apply-templates select="key('trans', $myId)" /> 
     </xsl:for-each> 
     </Transaction_data> 
    </xsl:copy> 
    </xsl:template> 

    <!-- omit the id element when copying a Transaction --> 
    <xsl:template match="Transaction/id" /> 

我想通過相同的連接節點執行與任意數量的xml文件相同的進程。以某種方式在單個xsl文件中可能嗎?

+0

如何指定文件名?在輸入XML文件中,通過參數還是別的東西? –

+0

是的,文件名是通過參數從外部給出的。因此,我們可以假設,file2,file3,... filen將包含剩餘的xml文件的路徑。 – user1728778

+0

是的,只需將'document()'的參數作爲一個節點集,每個節點都包含一個文檔的URI。 –

回答

2

如果要處理任意數量的輸入文件,則考慮傳遞文件名作爲參數的XML文檔,例如作爲參數傳遞文件files-to-process與內容都

<files> 
    <file>foo.xml</file> 
    <file>bar.xml</file> 
    <file>baz.xml</file> 
</files> 

然後有

<xsl:param name="files-url" select="'files-to-process.xml'"/> 
<xsl:variable name="files-doc" select="document($files-url)"/> 

,然後簡單地改變

<xsl:template match="Mail"> 
    <xsl:copy> 
     <!-- copy all children as normal --> 
     <xsl:apply-templates select="@*|node()" /> 
     <xsl:variable name="myId" select="id" /> 
     <Transaction_data> 
     <xsl:for-each select="document('transactions.xml')"> 
      <!-- process all transactions with the right ID --> 
      <xsl:apply-templates select="key('trans', $myId)" /> 
     </xsl:for-each> 
     </Transaction_data> 
    </xsl:copy> 
    </xsl:template> 

<xsl:template match="Mail"> 
    <xsl:copy> 
     <!-- copy all children as normal --> 
     <xsl:apply-templates select="@*|node()" /> 
     <xsl:variable name="myId" select="id" /> 
     <Transaction_data> 
     <xsl:for-each select="document($files-doc/files/file)"> 
      <!-- process all transactions with the right ID --> 
      <xsl:apply-templates select="key('trans', $myId)" /> 
     </xsl:for-each> 
     </Transaction_data> 
    </xsl:copy> 
    </xsl:template> 

這樣,你可以處理所有在作爲參數傳入的文檔中的files/file中命名的文件。

相關問題