Given the following XML:
<table>
<col width="12pt"/>
<col width="24pt"/>
<col width="12pt"/>
<col width="48pt"/>
</table>
How can I convert the width attributes to numeric values that can be used in mathematical expressions? So far, I have used substring-before to do this. Here is an example template (XSLT 2.0 only) that shows how to sum the values:
<xsl:template match="table">
<xsl:text>Col sum: </xsl:text>
<xsl:value-of select="sum(
for $w
in col/@width
return number(substring-before($w, 'pt'))
)"/>
</xsl:template>
Now my questions:
- Is there a more efficient way to do the conversion than
substring-before? - What if I don’t know the text after the numbers? Any way to do it without using regular expressions?
I found this answer from Dimitre Novatchev that provides a very clever XPATH solution that doesn’t use regex:
It uses the nested translate to strip all the numbers from the string, which yields all other characters, which are used as the values for the wrapping translate function to strip out and return just the number characters.
Applied to your template: