2017-07-27 52 views
2

轉換XML文件我有以下XML輸入轉化號碼羅馬數字:經由XSLT

<root> 
    <calc> 
     <arab>42</arab> 
    </calc> 
    <calc> 
     <arab>137</arab> 
    </calc> 
</root> 

我要輸出如下:

<root> 
    <calc> 
     <roman>XLII</roman> 
     <arab>42</arab> 
    </calc> 
    <calc> 
     <roman>CXXXVII</roman> 
     <arab>137</arab> 
    </calc> 
</root> 

通過編寫XSLT。到目前爲止,我編寫了這個XSLT,但是還需要做什麼來輸出正確的輸出?

<?xml version="1.0" encoding="UTF-8"?> 
    <xsl:transform 
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
     xmlns:xs="http://www.w3.org/2001/XMLSchema" 
     xmlns:num="http://whatever" 
     version="2.0" exclude-result-prefixes="xs num"> 

     <xsl:output method="xml" version="1.0" 
     encoding="UTF-8" indent="yes"/> 


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

    </xsl:transform> 

回答

4

嘗試:

<xsl:template match="calc"> 
    <xsl:copy> 
     <roman> 
      <xsl:number value="arab" format="I"/> 
     </roman> 
     <xsl:apply-templates/> 
    </xsl:copy> 
</xsl:template> 

數應爲1和3999之間

要驗證號碼是在範圍內1到3999,你可以這樣做:

<xsl:template match="calc"> 
    <xsl:copy> 
     <xsl:choose> 
      <xsl:when test="1 le number(arab) and number(arab) le 3999"> 
       <roman> 
        <xsl:number value="arab" format="I"/> 
       </roman> 
      </xsl:when> 
      <xsl:otherwise> 
       <xsl:message terminate="no">Please enter a number between 1 and 3999</xsl:message> 
      </xsl:otherwise> 
     </xsl:choose> 
     <xsl:apply-templates/> 
    </xsl:copy> 
</xsl:template> 

注意撒克遜至少支持羅馬數字高達9999: http://xsltransform.net/bEzjRKe

+0

你可能想包括' ..'輪的輸出,但爲什麼堅持XSLT 1或2?這個解決方案可以與任何一個一起工 – Flynn1179

+1

@ Flynn1179感謝您的接受.--至於版本,我問過,以便我知道在哪裏尋找答案。碰巧,答案也適用於XSLT 1.0,但情況並非總是如此。 –

+0

如何添加一些驗證?當輸入數字0應該是一個錯誤,並且XSLT可以處理高達3xxx的數字。所以羅馬數字所需的最高字母將是'M'。因此,例如任何高於3999的數字都應該失效。所以簡短的數字應該在1到3999之間。 – habed