z4y4ts
z4y4ts

Reputation: 2685

XSLT: How to round a list of floats in a attribute?

I have following input xml node:

<text bbox="143.430,683.264,147.982,695.231">foo</text>

What I want to have is:

<span class="ocrx_word" title="bbox 143 683 148 695">foo</span>

So far I can change commas to spaces and attribute name like so:

<xsl:template match="text">
  <xsl:variable name="bbox" select="translate(@bbox, ',', ' ')" />
  <span class='ocrx_word' title="bbox {$bbox}">
    <xsl:value-of select="."/>
  </span>
</xsl:template>

I see there are round() and str:split() (from EXSLT) functions, but I can't quite get how to mix them together to get what I want.

Upvotes: 0

Views: 183

Answers (2)

Tim C
Tim C

Reputation: 70598

I haven't been able to test this (as I don't have a XSLT processor to hand that supports EXSLT strings), but in theory, if lxml does, you want to do something like this...

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
                xmlns:str="http://exslt.org/strings"
                version="1.0">

  <xsl:output method="xml" indent="yes" />

  <xsl:template match="text">
    <xsl:variable name="bbox" select="str:tokenize(@bbox, ',')" />
    <span class="ocrx_word">
      <xsl:attribute name="title">
        <xsl:for-each select="str:tokenize(@bbox, ',')">
          <xsl:if test="position() > 1"> </xsl:if>
          <xsl:value-of select="round(number(.))" />
        </xsl:for-each>
      </xsl:attribute>
      <xsl:value-of select="."/>
    </span>
  </xsl:template>
</xsl:stylesheet>

Upvotes: 1

T.N Maurya
T.N Maurya

Reputation: 11

<xsl:template match="text">
<xsl:variable name="bbox" select="for $i in tokenize(@bbox,',')
return floor(number($i))" />
<span class='ocrx_word' title="bbox {$bbox}">
<xsl:value-of select="."/>
</span>
</xsl:template>

Upvotes: 0

Related Questions