通过使用translate添加属性值



我有下面的xml

<table>
<tgroup cols="7" align="left" colsep="1" rowsep="1">
<colspec colwidth="20pt" colname="c1"/>
<colspec colwidth="70pt" colname="c2"/>
<colspec colwidth="10pt" colname="c3"/>
<colspec colwidth="20pt" colname="c4"/>
<colspec colwidth="75pt" colname="c5"/>
</tgroup>
</table>

在这里我想添加所有的colwidth。当我使用sun()时,它显示Nan结果,因为colwidth在末尾有pt,我需要使用translate(),然后使用sum()函数,请告诉我如何做到这一点。

感谢

从本质上讲,您正在尝试做类似于"对于每个colspec,从其colwidth中去掉尾部的pt,并转换为一个数字,然后将所有得到的数字相加"的操作。在XSLT2.0中,您可以使用来完成此操作

sum(path/to/colspec/xs:integer(substring-before(@colwidth, 'pt')))

(如果colwidth不全是整数,则为xs:decimal)-path/to/colspec需要替换为从当前上下文节点到所有colspec元素集的正确路径,如果您当前在table元素上,则可能是tgroup/colspec,如果您目前在colspec元素之一上,则可以是../colspec

在XSLT1.0中,不能在单个XPath表达式中执行此操作,因为只能直接对节点集sum执行操作,不能在对单个值求和之前对其进行处理。在1.0中,我可能会选择带有累加器参数的尾部递归模板:

<xsl:template match="colspec" mode="sumwidth">
  <xsl:param name="total" select="0" />
  <xsl:apply-templates select="following-sibling::colspec[1]" mode="sumwidth">
    <xsl:with-param name="total"
         select="$total + substring-before(@colwidth, 'pt')" />
  </xsl:apply-templates>
</xsl:template>
<xsl:template match="colspec[not(following-sibling::colspec)]" mode="sumwidth">
  <xsl:param name="total" select="0" />
  <xsl:value-of select="$total + substring-before(@colwidth, 'pt')" />
</xsl:template>

然后使用调用

<xsl:apply-templates select="colspec[1]" mode="sumwidth" />

最新更新