找出 XSLT/XPATH 中变量的数据类型

Finding out the data type of a variable in XSLT/XPATH

似乎 xpath instance ofcastable as 运算符为我提供了一个布尔结果供我猜测...换句话说,我找不到发现变量类型的方法没有事先用 "yes or no" 条件猜测它。

假设我不知道类型是什么,我所能做的就是询问变量 $x 是否具有 xs:string 的数据类型,或者实际上是否是 xs:integer, 等等,对于所有可能的 xslt 数据类型,没有得到直接的答案。

  <xsl:function name="findType">
    <xsl:param name="var"/>
    <xsl:choose test="not(string(.) castable as xs:integer)">
     <xsl:when test="$var instance of xs:integer">
        <xsl:value-of select="'xs:integer'" />
     </xsl:when>
     <xsl:when test="$var instance of xs:string">
         <xsl:value-of select="'xs:string'" />
     </xsl:when>
     ...
     <xsl:otherwise>
        <xsl:value-of select="'unknown'" />
     </xsl:otherwise>
    </xsl:choose>
  </xsl:function>

有没有办法不用 switch-case 直接获取变量的数据类型?

查看三个函数中采用的方法 functx:node-kind http://www.xsltfunctions.com/xsl/functx_node-kind.html, functx:atomic-type http://www.xsltfunctions.com/xsl/functx_atomic-type.html and functx:sequence-type http://www.xsltfunctions.com/xsl/functx_node-kind.html of the functx library http://www.xsltfunctions.com/

具体到商业版(Saxon 的 PE 和 EE)你也可以发现 http://saxonica.com/html/documentation/functions/saxon/type-annotation.html and http://saxonica.com/html/documentation/functions/saxon/type.html 有用。

一般来说,一个XDM值属于任意数量的类型,问"the type"是什么是没有意义的。这在 XPath 3.0 映射中变得最为明显,其中类型系统是一个网格而不是层次结构变得非常清楚。

然而,对于绝大多数常用值,项目的 "the most specific user-visible type" 有一个相当直观的概念,这是因为这个概念是直观的而不是正式的,你会发现它是由扩展函数提供的而不是内置函数。 (另一个原因是 XDM 中的类型不是 first-class 对象,因此不清楚如何表示问题 "what is the type of X?" 的答案)。

对此功能的另一个反对意见是它很容易被滥用。如果 X 是整数,尽管整数是小数的子类型,但询问 if (typeof(X) == decimal) ... 将给出结果 "false"。如果 abs(X) 的实现更改为当 X 是整数时它 returns 是一个整数,那么询问结果是否为小数的现有代码将会中断。 "instance of" 运算符更安全。