2016-12-06 134 views
0

我是xslt的新手,並嘗試使用xslt轉換爲xml以下。我正在嘗試使用下面的xslt修改2個字段(一個是數字,另一個是字符串類型)。如何替換xslt中的字符串

<items> 
<item> 
    <item_id>27989498</item_id> 
    <service>Test Fee1</service> 
    <rate>350</rate> 
    <quantity>1</quantity> 
    <tax_rate>0</tax_rate> 
    <item_date>2010-11-17-05:00</item_date> 
</item> 
</items> 

XSLT:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 

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

<xsl:template match="rate[ . &gt; 0 ]"> 
    <xsl:copy>100</xsl:copy> 
</xsl:template> 

<xsl:template match="service[ . &eq; 'Test Fee1' ]"> 
    <xsl:copy>T1</xsl:copy> 
</xsl:template> 

輸出:

<items> 
<item> 
<item_id>27989498</item_id> 
<service>Test Fee1</service> 
<rate>100</rate> 
<quantity>1</quantity> 
<tax_rate>0</tax_rate> 
<item_date>2010-11-17-05:00</item_date> 
</item> 
</items> 

上面的XSLT被替換速度場正確,但對於字符串字段 「服務」 這不是更換預期值。如何比較和替換xslt中的字符串,因爲「eq」方法不起作用。

是否可以從值列表中選擇替換值而不是硬編碼?實施例:測試FEE1 = T1,測試費用2 = T2,測試費用3 = T3等

更新

在請求XML服務標籤將不會有來自系列的值,而不是這將是一個隨機值,需要用一些國家的州名來替代,如國家代碼應該被國家代碼替代,而不考慮區分大小寫。

示例:紐約= NY或紐約= NY,亞利桑那= AR等

+0

您以一種答案不再相應的方式改變了問題。請將它改回來,並擴大你的問題,而不是覆蓋它。 –

+0

我已經更新了有關更改的問題,能否請您提供一種方法,以便與不區分大小寫的情況進行比較,並從列表中選擇值? – springbatcher

+0

@springbatcher最好接受這裏給出的答案,並用新問題發佈一個新問題。無論如何,我們需要知道您是使用XSLT 1.0還是XSLT 2.0。在詢問XSLT時,請習慣於在xslt之外選擇其中一個標籤。 –

回答

1

假設一個XSLT 1.0(或更高版本)處理器只需使用match="service[. = 'Test Fee1' ]"。使用XSLT 2.0處理器,您也可以使用match="service[. eq 'Test Fee1' ]"match="rate[ . &gt; 0 ]"也可以簡化爲match="rate[ . > 0 ]"

1

一個在XSLT 1.0非常簡單的方法:

<xsl:template match="service[starts-with(., 'Test Fee') 
     and number(substring-after(., 'Test Fee')) &gt; 0]"> 
    <service> 
     <xsl:text>T</xsl:text> 
     <xsl:value-of select="substring-after(., 'Test Fee')"/> 
    </service> 
</xsl:template> 

這可能是進一步完善您的要求,具體取決於哪個值,您實際上是允許<服務>。