如何在XPath 3.1中区分Map、Array、String等类型?是否有类型检测函数?
XPath 3.1 数据类型区分与上下文节点类型检测
一、怎么区分各种数据类型?
XPath 3.1 自带了一套类型检测机制,结合内置函数和instance of表达式就能精准区分:
- 节点(含根节点):用
. instance of node()判断是否为节点,要特指根节点的话用. instance of document-node() - 空序列:要么用
. instance of empty-sequence(),要么直接判断not(exists(.)) - 字符串:
. instance of xs:string - 数字:通用判断用
. instance of xs:numeric,也可以细分整数(xs:integer)、小数(xs:decimal)这类具体数字类型 - Map:两种写法都行——
map:is-map(.)(需要引入http://www.w3.org/2005/xpath-functions/map命名空间),或者. instance of map(*) - Array:同理,
array:is-array(.)(引入http://www.w3.org/2005/xpath-functions/array命名空间),或者. instance of array(*)
二、实现你要的unknown:type-of(.)效果
XPath 3.1 没有直接返回这种简洁类型名称的内置函数,但用条件表达式拼一下就能实现:
示例代码
( root(), (), "a", 1, map{}, array{} ) ! ( if (. instance of document-node()) then "node" else if (. instance of empty-sequence()) then "sequence" else if (. instance of xs:string) then "string" else if (. instance of xs:numeric) then "number" else if (map:is-map(.)) then "map" else if (array:is-array(.)) then "array" else "unknown" )
运行结果
node sequence string number map array
三、上下文节点.的类型测试
直接把上面的检测逻辑用到.上就行,比如要判断当前上下文是不是Map,写map:is-map(.);要获取类型名称,就把上述条件判断里的.当成当前上下文节点用即可。
内容的提问来源于stack exchange,提问作者Fravadona
相关产品推荐
相关产品推荐

