使用XSLT将变量值作为元素名称

时间:2011-02-09 13:25:31

标签: xslt

我正在将一种格式的XML转换为另一种格式,我需要插入一个元素并将其命名为变量值。例如,我正在尝试使用XSLT的下面的语句,但我从处理器收到一个错误,说元素名称无效。

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">

    <xsl:output method="xml" version="1.0" encoding="utf-8" indent="no" omit-xml-declaration="no"/>

    <xsl:variable name="i" select="i"/>
    <xsl:variable name="b" select="b"/>
    <xsl:variable name="u" select="u"/>
    <xsl:variable name="s" select="s"/>
    <xsl:variable name="r" select="r"/>
    <xsl:variable name="m" select="m"/>
    <xsl:variable name="n" select="n"/>

<xsl:template match="/|comment()|processing-instruction()">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
      <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>

    <xsl:template match="//w:r">
        <xsl:if test="not(./descendant::w:i)">
         <xsl:variable name="i">0</xsl:variable>            
        </xsl:if>
        <xsl:if test="not(./descendant::w:b)">
         <xsl:variable name="b">0</xsl:variable>            
        </xsl:if>
        <xsl:if test="not(./descendant::w:u)">
         <xsl:variable name="u">0</xsl:variable>            
        </xsl:if>
        <xsl:if test="not(./descendant::w:caps)">
         <xsl:variable name="c">0</xsl:variable>            
        </xsl:if>

        <xsl:if test="not(contains($i,'0'))">
            <xsl:variable name="r" select="$i"></xsl:variable>
        <xsl:text>KARTHIKK</xsl:text>
        </xsl:if>
        <xsl:if test="not(contains($b,'0'))">
        <xsl:variable name="m" select="$r+$b"></xsl:variable>
        </xsl:if>
        <xsl:if test="not(contains($u,'0'))">
        <xsl:variable name="n" select="$m+$u"></xsl:variable>
        </xsl:if>
        <xsl:copy namespaces="no"><xsl:apply-templates/></xsl:copy>
<!--        <xsl:element name="{local-name(.)}"><xsl:element><xsl:value-of select="$n"/><xsl:apply-templates/></xsl:element></xsl:element>-->
    </xsl:template>


</xsl:stylesheet>

如何使用XSLT变量输出元素名称?

1 个答案:

答案 0 :(得分:55)

完全可以构造一个名称由变量值动态定义的元素:

<xsl:element name="{$vVar}">3</xsl:element>

如果变量$vVar的字符串值恰好是"Hello",那么上面会产生:

<Hello>3</Hello>

但是,如果变量$vVar的字符串值恰好是"123",则会引发错误,因为字符串"123"不是XML中的合法名称< /强>

目前尚不清楚代码中您想要动态构造元素的位置(并且代码中还有其他错误),但只需使用上述规则/示例,您将完全按照描述构造元素。 / p>