【问题标题】:how to count the number of elements in XML?如何计算 XML 中的元素数量?
【发布时间】:2020-02-17 09:59:32
【问题描述】:

我希望在数据库中获取有关 data 的基本元数据。具体来说,被根text 元素包围的line 元素的数量。

类似于我期望的 COUNT 返回 SQL —— 一个整数。

数据库:

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$ 

计算行数:

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$ 

代码:

xquery version "3.0";

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

【问题讨论】:

    标签: text count xquery basex flwor


    【解决方案1】:

    我想你只是想使用count(/text/line)

    【讨论】:

    • 谢谢,我认为这可以在 Java 上运行,但我希望也可以在 FLWOR 上运行。我认为这是导致 FLWOR 崩溃的线路迭代?我添加了一个“答案”来详细说明。
    • 我看不出使用 FLOWR 的任何理由,但如果是这样,您显然想要count(for ... return ...)
    • XQuery 初学者(尤其是那些来自 SQL 的初学者)犯的最大错误之一就是将 FLWOR 表达式作为每个问题的解决方案。对于绝大多数查询,FLWOR 表达式是多余的。
    【解决方案2】:

    从 Martin 的回答中,我发现 basex 本身很容易:

    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$ 
    

    但我也希望从 xq 文件中运行它:

    xquery version "3.0";
    
    count(
    for $line in db:open("people")
    return $line/text/line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 2011-08-12
      • 1970-01-01
      • 2018-02-15
      • 2017-12-16
      • 2019-09-07
      • 1970-01-01
      相关资源
      最近更新 更多