how to count the number of elements in XML?

泄露秘密 提交于 2021-01-29 15:12:12

问题


I'm looking to get basic metadata about the data within a database. Specifically, the number of line elements which are surrouned by the root text element.

Analogous to what I'd expect COUNT to return in SQL -- a single integer.

the database:

thufir@dur:~/flwor/group$ 
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> open people
Database 'people' was opened in 225.24 ms.
> 
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 215.13 ms.
> 
> exit
See you.
thufir@dur:~/flwor/group$ 

Counting the lines:

thufir@dur:~/flwor/group$ 
thufir@dur:~/flwor/group$ basex each.xq 
1
2
3
4
5
6
7
8
9
10
11
12
13thufir@dur:~/flwor/group$ 

code:

xquery version "3.0";

for $line in db:open("people")
for $index at $count in $line/text/line
return $count

回答1:


I suppose you simply want to use count(/text/line).




回答2:


From Martin's answer I see it's easy from within basex itself:

thufir@dur:~/flwor/group$ 
thufir@dur:~/flwor/group$ basex
BaseX 9.0.1 [Standalone]
Try 'help' to get more information.
> 
> open people
Database 'people' was opened in 208.33 ms.
> 
> xquery /
<text>
  <line>people</line>
  <line>joe</line>
  <line>phone1</line>
  <line>phone2</line>
  <line>phone3</line>
  <line>sue</line>
  <line>cell4</line>
  <line>home5</line>
  <line>alice</line>
  <line>atrib6</line>
  <line>x7</line>
  <line>y9</line>
  <line>z10</line>
</text>
Query executed in 237.69 ms.
> 
> xquery count(/text/line)
13
Query executed in 20.55 ms.
> 
> exit
See you.
thufir@dur:~/flwor/group$ 

but I was also looking to run it from an xq file:

xquery version "3.0";

count(
for $line in db:open("people")
return $line/text/line)


来源:https://stackoverflow.com/questions/60259916/how-to-count-the-number-of-elements-in-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!