Hobbes
Hobbes

Reputation: 2125

String operations on a sequence

I have an XML that contains a series of images and their widths:

<p>
    <image width="10cm"/>
    <image width="3cm"/>
</p>

I need to calculate the total width of these images. When I have only 1 image, this is simple:

<template match="p">
    <xsl:variable name="imgwidth">
        <xsl:value-of select="number(substring-before(image/@width,'cm'))"/>

Naively, I tried expanding this to accommodate more images:

<xsl:value-of select="sum(number(substring-before(image/@width,'cm')))"/>

When I run this on my sample, I get an error message:

A sequence of more than one item is not allowed as the first argument of fn:substring-before() ("10cm", "3cm")

I've done some searches, but can't figure out how to run the substring-before on each image node inside my <p>.

Upvotes: 0

Views: 46

Answers (1)

Tim C
Tim C

Reputation: 70638

In XSLT 2.0, you can write this...

<xsl:value-of select="sum(image/number(substring-before(@width,'cm')))"/>

Or, perhaps this...

<xsl:value-of select="sum(for $i in image return number(substring-before($i/@width, 'cm')))"/>

Upvotes: 1

Related Questions