Reputation: 425
I have nodes that contain numbers that I would like to cast to a number and use mod. For example:
<item>
<num>1</num>
</item>
<item>
<num>2</num>
</item>
<item>
<num>3</num>
</item>
I've tried:
num mod 3 -- returns NaN
number(num) mod 3 -- returns NaN
number(string(num)) -- returns NaN
Any idea if this can be done? Even if there was a way to convert to ASCII, I would take it
Thanks in advance!
Upvotes: 4
Views: 3337
Reputation: 243529
I've tried:
num mod 3 -- returns NaN number(num) mod 3 -- returns NaN number(string(num)) -- returns NaN
Any idea if this can be done?
As no complete XML document is provided, here are my two guesses:
The context node for the relative expressions has no num
children. The solution is to assure that the context node is the correct one, or to use absolute XPath expression(s).
The not-shown XML document is in a default namespace. In this case the solution is to "register a namespace" (associate a string-prefix to the default namespace, say "x"
) and then replace in your expressio(s) num
with x:num
.
Upvotes: 1
Reputation: 43823
number(num) mod 3
should work. The following example files output 1 2 0
as expected.
(saved as input.xml
)
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="mod_test.xsl"?>
<items>
<item>
<num>1</num>
</item>
<item>
<num>2</num>
</item>
<item>
<num>3</num>
</item>
</items>
(saved as mod_text.xsl
)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="//item">
<xsl:value-of select="number(num) mod 3"/>
</xsl:template>
</xsl:stylesheet>
Note: just num mod 3
in the select also works.
For reference, here is the relevant section in the documentation.
Upvotes: 2