2011-10-15 43 views
-1

在HTML中,分別有下劃線和粗體標記,分別爲<u><b>。假設我創建了一個標籤來完成其中的一個或兩個,然後如何使用XSLT來解釋它。如何使用XSLT讀取多功能XML標籤?

例如 -

<Line type="B">stackoverflow</Line> 
<Line type="U">stackoverflow</Line> 
<Line type="BU">stackoverflow</Line> 

的HTML輸出應該是這樣的 -

<b>stackoverflow</b> 
<u>stackoverflow</u> 
<b><u>stackoverflow</b></u> 

我想這個功能纔會使用XSLT部分。

回答

1

執行此操作的一種方法是使用遞歸模板,該遞歸模板遞歸檢查該行的類型屬性的每個字母。所以,去創造你要做的第一件以下(其中$ type是包含屬性值的變量):

<xsl:element name="{substring($type, 1, 1)}"> 

,那麼你會遞歸調用的命名模板與屬性值的剩餘部分

<xsl:call-template name="Line"> 
    <xsl:with-param name="type" select="substring($type, 2)"/> 
</xsl:call-template> 

因此,鑑於以下XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="Line" name="Line"> 
     <xsl:param name="type" select="@type"/> 
     <xsl:choose> 
     <xsl:when test="not($type)"> 
      <xsl:value-of select="."/> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:element name="{substring($type, 1, 1)}"> 
       <xsl:call-template name="Line"> 
        <xsl:with-param name="type" select="substring($type, 2)"/> 
       </xsl:call-template> 
      </xsl:element> 
     </xsl:otherwise> 
     </xsl:choose> 
    </xsl:template> 
</xsl:stylesheet> 

當應用於以下XML

<Lines> 
    <Line type="B">stackoverflow</Line> 
    <Line type="U">stackoverflow</Line> 
    <Line type="BU">stackoverflow</Line> 
    <Line>No format</Line> 
</Lines> 

會輸出如下

<Lines> 
    <B>stackoverflow</B> 
    <U>stackoverflow</U> 
    <B><U>stackoverflow</U></B> 
    No format 
</Lines> 

注,停止元素是輸出在這種情況下,只需添加下面的模板到XSLT:

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