Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath - extract numeric value out of string

<Description>this is my value 822880494 this is my value</Description>

I'm quite new to xpath, xml and stylevision so this might be a basic problem.

I am using stylevision 2010 and xpath to create an sps/xslt for an schema.

In the above node you can see there is a numeric value inside the node and I want to extract that value and turn it into a link in my pdf/html. The problem is that i cant seem to extract it. Substring is not an option since the length of the value and the position of the numeric value inside it varies.

Some will probably think that the schema is badly composed and that the numeric value should be in a seperate node/attribute/... There is nothing I can do about that since this schema is provided by another company.

Thanks in advance!

like image 385
BBQ Avatar asked Jan 17 '12 07:01

BBQ


1 Answers

Use this simple XPath 1.0 expression:

translate(.,translate(., '0123456789', ''), '')

Here is a complete XSLT 1.0 solution:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*">
     <xsl:value-of select=
      "translate(.,translate(., '0123456789', ''), '')"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:

<Description>this is my value 822880494 this is my value</Description>

the wanted, correct result is produced:

822880494

Explanation:

This is known as the Double Translate Method first proposed by Michael Kay. It consists of two nested calls to the translate() function:

  1. Inner translate(). This produces all characters of the string, except digits.

  2. Outer translate(). This deletes from the string all characters produced by the inner translate(). What remains is just the wanted characters (the digits).

like image 196
Dimitre Novatchev Avatar answered Sep 19 '22 12:09

Dimitre Novatchev