2014-04-24 75 views
0

我想一個XML文件轉換到另一個XML文件,在一些情況下,添加了額外內容不提供內容添加到XML。XSLT:根據條件

我的XML看起來是這樣的:

<bookstore> 
    <book> 
     <title>Book1</title> 
     <author>Author1</author> 
     <chapters> 
      <chapter> 
        <ch-name>BLABLA</ch-name> 
        <ch-number>1</ch-number> 
      </chapter> 
     </chapters> 
    </book> 
    <book> 
     <title>Book2</title> 
     <author>Author2</author> 
     <chapters> 
      <chapter> 
        <ch-name>Test</ch-name> 
        <ch-number>1</ch-number> 
      </chapter> 
     </chapters> 
    </book> 
    <book> 
     <title>Book3</title> 
     <author>Author3</author> 
    </book> 
</bookstore> 

現在,我要的章節元素(及其子元素)添加到書籍,它不存在,創建某種違約。

我的XSLT是這樣的:

<dns:template match="book[not(exists(chapters))]"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|*"/> 
    </xsl:copy> 
    <chapters> 
      <chapter> 
       <ch-name>default</ch-name> 
       <ch-number>default</ch-number> 
      </chapter> 
    </chapters> 
</dns:template> 

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

然而,當我嘗試這一個在線編輯器,沒有任何更改。 dns命名空間應該支持not(exists)部分。

有什麼錯我的XSLT?

感謝您給予的幫助!

+0

'dns:template'?你的意思是'xsl:template'? –

+0

沒有因爲那時我不能使用沒有(存在)的條款,可以嗎?他們在另一個命名空間 – Tcanarchy

回答

2

更改「DNS」前綴「XSL」(當然你也可以有相同的命名空間再次定義的前綴,但不推薦)。如果您使用XSLT1.0,則不存在「exists()」函數。 另外,「章節」需要在裏面。 您可以使用此xslt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" indent="yes"/> 
<xsl:strip-space elements="*"/> 
<xsl:template match="book[not(chapters)]"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|*"/> 
     <chapters> 
      <chapter> 
       <ch-name>default</ch-name> 
       <ch-number>default</ch-number> 
      </chapter> 
     </chapters> 
    </xsl:copy> 

</xsl:template> 

<xsl:template match="@* | *"> 
    <xsl:copy> 
     <xsl:apply-templates select="@* | * | text()"/> 
    </xsl:copy> 
</xsl:template> 
</xsl:stylesheet> 
+0

謝謝您指定的,問題是事實,章節是外面的xsl:副本。 – Tcanarchy