动态创建属性

Create a attribute dynamically

我正在编写一个 xsl 脚本,我需要在其中动态创建属性。

这是我的示例代码。

 <Table BORDERLINESTYLE="solid" BOTTOMMARGIN="12" NOTEGROUPSPACING="single" CELLPADDING="0" CELLSPACING="0" WIDTH="504"></Table>

此处 BORDERLINESTYLE 可能对所有 Table 标签可用,也可能不可用。我希望输出是这样的。

<table style="border-style:solid; border-margin:12px; width:504px"></table>

这是我尝试过的两件事。

1。创建属性

 <table>
    <xsl:if test="./@BORDERLINESTYLE">
        <xsl:attribute name="border" select="'1px solid'"/>
    </xsl:if>
    
     <xsl:if test="./@WIDTH">
        <xsl:attribute name="width" select="concat(./@WIDTH, 'px')"/>
    </xsl:if>
    
     <xsl:if test="./@BOTTOMMARGIN">
        <xsl:attribute name="border" select="'1px solid'"/>
    </xsl:if>
   <xsl:apply-templates/>
 </table>

我得到的输出如下。

<table border="1px solid" width="504px">

2。内联添加

<table style="width:{current()/@WIDTH,'px'}; border:{./@BORDERLINESTYLE}; margin-bottom: {./@BOTTOMMARGIN, 'px'}; margin-top:{./@TOPMARGIN, 'px'}; "></table>

并且输出如下,其中包含一些空白值,例如 margin-top

<table style="width:504 px; border:solid; margin-bottom: 12 px; margin-top:px; ">

如何根据 XML 中提供的属性向 style 添加样式?

我正在使用 XSLT2.0。

使用 if else 函数

例如

margin-top: {if(//@TOPMARGIN!=0) then {./@TOPMARGIN, 'px'} else '12px'}

我会用这样的东西:

  <xsl:if test="@BORDERLINESTYLE|@WIDTH|@BOTTOMMARGIN|@TOPMARGIN">
    <xsl:attribute name="style">
      <xsl:if test="@BORDERLINESTYLE">
        <xsl:text>border:1px solid;</xsl:text>
      </xsl:if>
      <xsl:if test="@WIDTH">
        <xsl:value-of select="concat('width:',@WIDTH, 'px;')"/>
      </xsl:if>
      <xsl:if test="@BOTTOMMARGIN">
        <xsl:value-of select="concat('margin-bottom:',@BOTTOMMARGIN, 'px;')"/>
      </xsl:if>
      <xsl:if test="@TOPMARGIN">
        <xsl:value-of select="concat('margin-top:',@TOPMARGIN, 'px;')"/>
      </xsl:if>
    </xsl:attribute>
  </xsl:if>

并根据将这些源属性映射到样式属性的业务规则相应地更改代码。

顺便说一句:./@@

相同

I need to create the attribute dynamically.

实际上,您想要动态地填充 属性 - 这可以通过将模板应用于您要使用的每个输入属性来完成:

<xsl:template match="Table">
    <table>
        <xsl:attribute name="style">
            <xsl:apply-templates select="@BORDERLINESTYLE | @BOTTOMMARGIN | @WIDTH"/>
        </xsl:attribute>
    </table>
</xsl:template>

<xsl:template match="@BORDERLINESTYLE">
    <xsl:text>border-style:</xsl:text>
    <xsl:value-of select="."/>
    <xsl:text>; </xsl:text>
</xsl:template>

<xsl:template match="@BOTTOMMARGIN">
    <xsl:text>border-margin:</xsl:text>
    <xsl:value-of select="."/>
    <xsl:text>px; </xsl:text>
</xsl:template>

<xsl:template match="@WIDTH">
    <xsl:text>width:</xsl:text>
    <xsl:value-of select="."/>
    <xsl:text>; </xsl:text>
</xsl:template>