2009-12-01 88 views
0

我有一個關於XSL轉換的問題。讓我們採取一個實例(在srcML)表示在C的typedef枚舉:如何爲srcML創建XSLT轉換?

<typedef>typedef <type><enum>enum <name>SomeEnum</name> 
<block>{ 
<expr><name>Value0</name> = 0</expr>, 
<expr><name>Value1</name> = <name>SOMECONST</name></expr>, 
<expr><name>Value2</name> = <name>SOMECONST</name> + 1</expr>, 
<expr><name>ValueTop</name></expr> 
}</block></enum></type> <name>TSomeEnum</name>;</typedef> 

C版:

typedef enum SomeEnum 
{ 
    Value0 = 0, 
    Value1 = SOMECONST, 
    Value2 = SOMECONST + 1, 
    ValueTop 
} TSomeEnum; 

如何定義一個<xsl:template>以去除與所述線,例如,Value2

如何定義一個<xsl:template>刪除最後一行(使用ValueTop),包括前面的逗號?

回答

1

由於輸入XML的「散佈文本」性質,這有點棘手。特別是逗號處理不是微不足道的,我提出的解決方案可能是錯誤的(即使它適用於此特定輸入)。我建議給逗號處理部分更多思考,因爲C語法很複雜,我對srcML不太瞭解。

無論如何,這是我的嘗試。

<xsl:stylesheet 
    version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:src="http://www.sdml.info/srcML/src" 
    xmlns="http://www.sdml.info/srcML/src" 
> 
    <!-- the identity template copies everything as is --> 
    <xsl:template match="node() | @*"> 
    <xsl:copy> 
     <xsl:apply-templates select="node() | @*" /> 
    </xsl:copy> 
    </xsl:template> 

    <!-- empty templates will remove any matching elements from the output --> 
    <xsl:template match="src:expr[src:name = 'Value2']" /> 
    <xsl:template match="src:expr[last()]" /> 

    <!-- this template handles the commata after expressions --> 
    <xsl:template match="text()[normalize-space() = ',']"> 
    <!-- select the following node, but only if it is an <expr> element --> 
    <xsl:variable name="expr" select="following-sibling::*[1][self::src:expr]" /> 

    <!-- apply templates to it, save the result --> 
    <xsl:variable name="check"> 
     <xsl:apply-templates select="$expr" /> 
    </xsl:variable> 

    <!-- if something was returned, then this comma needs to be copied --> 
    <xsl:if test="$check != ''"> 
     <xsl:copy /> 
    </xsl:if> 
    </xsl:template> 

</xsl:stylesheet> 

我的輸入是(I用於示例的目的的srcML命名空間):

<unit xmlns="http://www.sdml.info/srcML/src"> 
<typedef>typedef <type><enum>enum <name>SomeEnum</name> 
<block>{ 
<expr><name>Value0</name> = 0</expr>, 
<expr><name>Value1</name> = <name>SOMECONST</name></expr>, 
<expr><name>Value2</name> = <name>SOMECONST</name> + 1</expr>, 
<expr><name>ValueTop</name></expr> 
}</block></enum></type> <name>TSomeEnum</name>;</typedef> 
</unit 

和結果:

<unit xmlns="http://www.sdml.info/srcML/src"> 
<typedef>typedef <type><enum>enum <name>SomeEnum</name> 
<block>{ 
<expr><name>Value0</name> = 0</expr>, 
<expr><name>Value1</name> = <name>SOMECONST</name></expr> 
}</block></enum></type> <name>TSomeEnum</name>;</typedef> 
</unit>