2013-04-23 48 views
0

我必須在XSL 1.0中編寫一個小型的通用轉換函數,在書名涉及「NC」時將負價格轉爲正值。價格可以發生在多個/任何級別。我必須遇到負面信號,並將其轉化爲任何形式的XML。請建議。車削價格爲正數

XML的

<Books> 
<Book> 
    <Name>NC</Name> 
    <Price>-100.50</Price> 
</Book> 
<Book> 
    <Name>B1</Name> 
    <Pr>450.60</Pr> 
</Book> 
<Book> 
    <Name>C1</Name> 
    <Price>35.20</Price> 
</Book> 
<Book> 
    <Name>D1</Name> 
    <P>5</P> 
</Book> 
</Books> 
+0

請顯示[你試過的東西](http://www.whathaveyoutried.com/) – Borodin 2013-04-23 11:22:54

回答

1

如果你想文本內容的價格與數量小於零,屬於書與「NC」的名稱元素。在這種情況下,您只需要進行以下模板匹配

<xsl:template match="Book[Name='NC']/Price[number(.) &lt; 0]/text()"> 

然後您可以添加代碼以將負值轉化爲正值。

嘗試以下XSLT

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

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

<xsl:template match="Book[Name='NC']/Price[number(.) &lt; 0]/text()"> 
    <xsl:value-of select="format-number(0 - number(.), '0.00')" /> 
</xsl:template> 

</xsl:stylesheet> 

當適用於您的XML,下面是輸出

<Books> 
    <Book> 
     <Name>NC</Name> 
     <Price>100.50</Price> 
    </Book> 
    <Book> 
     <Name>B1</Name> 
     <Pr>450.60</Pr> 
    </Book> 
    <Book> 
     <Name>C1</Name> 
     <Price>35.20</Price> 
    </Book> 
    <Book> 
     <Name>D1</Name> 
     <P>5</P> 
    </Book> 
</Books> 

注意使用identity transform的複製現有元素。