2011-08-31 60 views
1

我有兩個文件。數據中有一些重疊,但我想從file2中提取特定信息並添加到file1。使用XSL結合基於唯一節點的兩個xml文件

File1.xml看起來這樣:

<content> 
    <book> 
    <id>111aaa</id> 
    <author>John Doe</author> 
    <title>This is a book</title> 
    <price>$10.00</price> 
    </book> 
    <book> 
    <id>111bbb</id> 
    <author>Jane Doe</author> 
    <title>This is another book</title> 
    <price>$20.00</price> 
    </book> 
</content> 

File2.xml看起來這樣:

<content> 
    <book> 
    <id>111aaa</id> 
    <author>John Doe</author> 
    <year>2011</year> 
    <pages>100</pages> 
    </book> 
    <book> 
    <id>111bbb</id> 
    <author>Jane Doe</author> 
    <year>2010</year> 
    <pages>200</pages> 
    </book> 
</content> 

我想從文件2拉動今年和頁面標籤,並將其添加到file1和有一個輸出file3.xml文件,看起來這樣的:

<content> 
    <book> 
    <id>111aaa</id> 
    <author>John Doe</author> 
    <title>This is a book</title> 
    <year>2011</year> 
    <pages>100</pages> 
    <price>$10.00</price> 
    </book> 
    <book> 
    <id>111bbb</id> 
    <author>Jane Doe</author> 
    <title>This is a another book</title> 
    <year>2010</year> 
    <pages>200</pages> 
    <price>$20.00</price> 
    </book> 
</content> 

我使用命令行運行xsltproc的:

xsltproc的transform.xsl file1.xml> file3.xml

我有我的XSL以下塊,但它只是相結合的第一本書的數據。你知道如何編寫xsl來瀏覽每本書嗎?

<xsl:choose> 
          <xsl:when test="document('file2.xml')/content/book/id = id"> 
           <xsl:for-each select="document('file2.xml')/content/book"> 
           <xsl:element name="pages"> 
           <xsl:value-of select="document('file2.xml')/content/book/pages"/> 
           </xsl:element> 
           <xsl:element name="year"> 
            <xsl:value-of select="document('file2.xml')/content/book/year"/> 
           </xsl:element> 
            </xsl:for-each> 
          </xsl:when> 
          <xsl:otherwise></xsl:otherwise> 
         </xsl:choose> 
+1

確保接受最好的解決您的問題的答案。 –

+0

@empo:他不知道「接受答案」是什麼意思。 –

回答

1

您正在尋找這方面的內容,我想。修復語法留給你。

<xsl:for-each select="book"> 
    <xsl:copy> 
    <xsl:apply-templates/> 
    <xsl:variable name="id" select="string(id)"/> 
    <xsl:for-each select="document('file2.xml')/content/book[string(id)=$id]/*"> 
     <xsl:apply-templates/><!-- Add in a choose here if you just want to pick out certain fields, or in the for-each above --> 
    </xsl:for-each> 
    </xsl:copy> 
</xsl:for-each> 
1

交叉引用使用的關鍵問:

<xsl:key name="k1" match="book" use="id"/> 

<xsl:template match="@* | node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="book"> 
    <xsl:variable name="id" select="id"/> 
    <xsl:apply-templates select="@* | id | author"/> 
    <xsl:for-each select="document('file2.xml')"> 
    <xsl:apply-templates select="key('k1', $id)/year | key('k1', $id)/pages"/> 
    </xsl:for-each> 
    <xsl:apply-templates select="price"/> 
</xsl:template> 
+0

關鍵作品奇妙。謝謝一堆 – Doug