2014-04-14 32 views
1

XSLT 1.0。處理具有不同命名空間的根節點

源XML文件:

<?xml version="1.0" encoding="UTF-8"?> 
<playlist xmlns="http://xspf.org/ns/0/" version="1"> 
    <trackList> 
     <track> 
      <location>1/Kosheen/Independence/01;Addict.flac</location> 
      <title>Addict</title> 
      <creator>Kosheen</creator> 
      <album>Independence</album> 
      <duration>286000</duration> 
      <image>1/Kosheen/Independence/cover.jpg</image> 
     </track> 
    </trackList> 
</playlist> 

XSLT樣式表文件:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output method="xml" encoding="utf-8" omit-xml-declaration="no" indent="no" /> 

    <xsl:template match="/playlist/trackList"> 
     <tracks> 
      <xsl:apply-templates select="track"/> 
     </tracks> 
    </xsl:template> 

    <xsl:template match="/playlist/trackList/track"> 
     <track> 
      <xsl:copy-of select="location"/> 
      <xsl:copy-of select="title"/> 
      <xsl:copy-of select="creator"/> 
      <xsl:copy-of select="album"/> 
     </track> 
    </xsl:template> 

</xsl:stylesheet> 

除非我刪除樣式表中的模板不應用於根playlist節點xmlns屬性。

我想輸出XML文件是免費的XSPF命名空間。

我應該如何更新樣式表來處理根節點的xspf命名空間?

+0

如果您搜索「默認XSLT命名空間」,您會發現676個問題的答案,其中大多數都是正確的。 –

回答

2

您需要添加一個聲明爲您的命名空間,並指定一個前綴,以便你可以參考的元素源文檔中:

xmlns:ns1="http://xspf.org/ns/0/" 

由於您的結果文檔也是在相同的命名空間,你把它聲明作爲默認的命名空間,以及:

xmlns="http://xspf.org/ns/0/" 

現在你指的是元素源XML的前綴:ns1:playlist,例如。

這裏是與命名空間的樣式表補充說:

<xsl:stylesheet 
    xmlns="http://xspf.org/ns/0/" 
    xmlns:ns1="http://xspf.org/ns/0/" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    exclude-result-prefixes="ns1" 
    version="1.0"> 

    <xsl:output method="xml" encoding="utf-8" omit-xml-declaration="no" indent="no" /> 

    <xsl:template match="/ns1:playlist/ns1:trackList"> 
     <tracks> 
      <xsl:apply-templates select="ns1:track"/> 
     </tracks> 
    </xsl:template> 
    <xsl:template match="/ns1:playlist/ns1:trackList/ns1:track"> 
     <track> 
      <xsl:copy-of select="ns1:location"/> 
      <xsl:copy-of select="ns1:title"/> 
      <xsl:copy-of select="ns1:creator"/> 
      <xsl:copy-of select="ns1:album"/> 
     </track> 
    </xsl:template> 
</xsl:stylesheet> 

更新

如果你的成績必須在no-namespace,可以去掉前綴的xmlns,但你不能使用copy-of(因爲它複製完整節點,包括名稱空間 - xmlns聲明將出現在每個節點中)。如果您的孩子元素都有唯一的文字,你可以替換:

<xsl:copy-of select="ns1:location"/> 

<location><xsl:value-of select="ns1:location"/></location> 

然後你可以從<xsl:stylesheet>刪除默認xmlns

+0

輝煌 - 謝謝。結果的根節點「跟蹤」節點具有xspf.org xmlns和xmlns:xspf attributes/namespace - 是否有可能擺脫這些? –

+0

由於在結果中沒有使用前綴,因此可以將'exclude-result-prefixes =「ns1」'添加到''中。我編輯了上面的內容。 – helderdarocha

+0

你*可以*擺脫'xmlns'。在這種情況下,您可以從'xsl:stylesheet'中移除'xmlns',但也必須有選擇地複製您的節點(不要使用'copy-of'),因爲您必須刪除名稱空間。如果從默認結果樹中刪除'xmlns',則''和''將處於無名稱空間,但使用'copy-of'複製的節點將位於xspf名稱空間中。 – helderdarocha

相關問題