2016-08-15 38 views
1

我有兩個.xml文件,這需要連接我如何加入2 XML在1 XSL

第一個文件是Song.xml如下所示:

<Songs> 
    <Song> 
    <SongID>1</SongID> 
    <SongName>We dont talk anymore</SongName> 
    <Author>M-TP</Author> 
    <UploadBy>admin</UploadBy> 
    <GerneCode>1</GerneCode> 
    </Song> 
</Songs> 

和Gerne.xml從產生架構

<ns2:gernes xmlns="http://www.w3.org/2001/XMLSchema/playlist" xmlns:ns2="https://xml.netbeans.org/schema/genses"> 
    <ns2:gerne> 
     <GerneCode>1</GerneCode> 
     <GerneName>Pop</GerneName>   
     <Image>img-pop.jpg</Image> 
    </ns2:gerne> 
</ns2:gerne> 

我想加入一個XSL內這些.xml檔案,這將增加該GerneName,每首歌曲的是馬tch GerneName在Gerne.xml之內。

結果IM試圖讓應該是這樣的:

<Songs> 
     <Song> 
     <SongID>1</SongID> 
     <SongName>We dont talk anymore</SongName> 
     <Author>M-TP</Author> 
     <UploadBy>admin</UploadBy> 
     <GerneName>Pop</GerneName> 
     <GerneCode>1</GerneCode> 
     </Song> 
</Songs> 

誰能幫助我?任何例如或關鍵字我應該查找什麼問題?

+0

要開始,請閱讀'Gerne.xml'使用[文件](http://www.w3schools.com/xsl/func_document.asp)功能,得到了'GerneCode','GerneName',看看' GerneCode'當前元素的'GerneCode'匹配'Songs.xml'和'Songs.xml'當前的元素複製'GerneCode','GerneName'。您可以使用[的XPathFactory(https://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/XPathFactory.html)的XPath表達式和TransformerFactory中,請參閱:https://docs.oracle .COM/JavaSE的/ 7 /文檔/ API /使用javax/XML /轉化你的XML一旦你的XSL轉換/ TransformerFactory.html)。 – SomeDude

+0

你可以使用XSLT 2.0嗎? –

回答

0

假設你是限於XSLT 1.0,你可以這樣做:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:pl="http://www.w3.org/2001/XMLSchema/playlist" 
xmlns:ns2="https://xml.netbeans.org/schema/genses" 
exclude-result-prefixes="pl ns2"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:variable name="lookup-path" select="'Gerne.xml'" /> 
<xsl:key name="genre" match="ns2:gerne" use="pl:GerneCode" /> 

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

<xsl:template match="GerneCode"> 
    <xsl:variable name="code" select="." /> 
    <!-- switch context to the other file --> 
    <xsl:for-each select="document($lookup-path)"> 
     <GerneCode> 
      <xsl:value-of select="key('genre', $code)/pl:GerneName" /> 
     </GerneCode> 
    </xsl:for-each> 
    <xsl:copy-of select="."/> 
</xsl:template> 

</xsl:stylesheet> 

這是假設你告訴你的XSLT處理器處理Song.xml文件,並傳遞路徑Gerne.xml文件作爲參數。

請注意,您發佈的Gerne.xml文檔不是格式良好的XML(沒有</ns2:gernes>結束標籤)。


順便說一句,正確的術語是「流派」 - 而不是「gerne」或「gense」。

+0

謝謝。此解決方案有效。對不起,我的英語不好,我的詞彙量有問題。 –

+0

@BeansVănQuý如果您的問題得到解答,請通過接受答案關閉它。 –