I am trying to find the largest element using length and value
my input xml:
<?xml version="1.0" encoding="utf-8" ?>
<section>
<root>
<data><label.designator>31.</label.designator></data>
<data><label.designator>31.5.</label.designator></data>
<data><label.designator>49.5.</label.designator></data>
<data><label.designator>50.</label.designator></data>
</root>
</section>
I am trying with below xslt code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:math="http://www.w3.org/2005/xpath-functions/math"
xmlns:map="http://www.w3.org/2005/xpath-functions/map"
xmlns:array="http://www.w3.org/2005/xpath-functions/array"
exclude-result-prefixes="#all"
version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="root">
<xsl:variable name="Length">
<xsl:for-each select="data/label.designator">
<xsl:sort select="string-length(.)" order="descending" data-type="number"/>
<xsl:if test="position() = 1">
<xsl:value-of select="string-length(.)"/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
Max string length is: <xsl:value-of select="$Length"/><br/>
<xsl:variable name = "list" select="child::data[last()]/label.designator/string-length(.) = $Length" />
Value is : <xsl:value-of select="$list"/>
</xsl:template>
</xsl:stylesheet>
here I am getting true or false instead i should get the value, in my case it is 49.5 (it is matching both criteria's longest(i have 2 here 31.5. and 49.5.) & biggest(out of 2 49.5. is the highest one)
expected output:
<?xml version="1.0" encoding="UTF-8"?>
<section>
Max string length is: 5<br/> and value is : 49.5.
</section>
CodePudding user response:
At https://www.w3.org/TR/xpath-functions-31/#highest-lowest you will find example code for a function called eg:highest()
. If you add this function to your stylesheet, you can then call eg:highest(//label.designator, string-length#1)
to obtain the element or elements with greatest string-length.
CodePudding user response:
If it's acceptable to remove the trailing period in order to calculate the max value, then you could do:
XSLT 3.0
<xsl:stylesheet version="3.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
expand-text="yes">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/section">
<xsl:variable name="data" select="root/data/label.designator" />
<xsl:variable name="max-len" select="max($data/string-length())" />
<xsl:variable name="max-val" select="max($data[string-length()=$max-len]/replace(., '\.$', ''))" />
<section>Max string length is: {$max-len}<br/> and value is : {$max-val}</section>
</xsl:template>
</xsl:stylesheet>
Result
<?xml version="1.0" encoding="UTF-8"?>
<section>Max string length is: 5<br/> and value is : 49.5</section>
However, this result shows a discrepancy between the original string-length of 5 and the adjusted value's string-length of 4.