Xpath Cast node for mod number

I have nodes that contain numbers that I would like to attribute to a number and use mod. For instance:

<item> <num>1</num> </item> <item> <num>2</num> </item> <item> <num>3</num> </item> 

I 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!

+4
source share
2 answers

number(num) mod 3 should work. The following sample files output 1 2 0 as expected.

XML

(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> 

XSL

(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 select also works.

For reference, here is the relevant section in the documentation.

+2
source

I tried:

 num mod 3 -- returns NaN number(num) mod 3 -- returns NaN number(string(num)) -- returns NaN 

Any idea if this can be done?

Since the full XML document is not presented, here are my two guesses :

  • The node context for relative expressions does not have num children . The solution is to make sure the node context is correct, or use an absolute XPath expression.

  • An XML document is not shown in the default namespace . In this case, the solution should "register the namespace" (associate the string prefix with the default namespace, for example, "x" ), and then replace (s) num with x:num in your expressions.

+1
source

Source: https://habr.com/ru/post/1388414/


All Articles