xquery- 在单个父级中获取这些元素的计数,这些元素不为空 [英] xquery- getting count of those elements, within a single parent, which are not empty

查看:25
本文介绍了xquery- 在单个父级中获取这些元素的计数,这些元素不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下 XML--

<p>文本 sihdfaif

<p/><p>文本 sihdfaif

<p/><p>文本 sihdfaif

<p>文本 sihdfaif

<p>文本 sihdfaif

现在,我想获取其中包含一些文本的 p 元素的数量.. 在这种情况下,该值 = 5(有 2 个 'p' 元素为空)

这是我想出的 XQuery--

 let $claims_main := $doc//div[@id="test"]让 $claims := $doc//div[@id="test"]/p让 $n := count($claims)其中 $claims_main/p != ''返回 $n

然而,我从上面得到的结果是 7,即包括空的 'p' 元素.

我想到的另一种方法是对所有p"元素使用 for 循环,但在这种情况下,我如何检索循环的元素总数?如果我在这种情况下使用计数,那么我只会得到 [1,1,1,1,1]- 即.每个 p 元素的计数(因为在 for 循环中,计数将针对每个 'p' 元素,而不是 div 本身)...

解决方案

由于问题专门针对p 元素,其中包含一些文本", 这里是如何精确获取这样的 p 元素的数量:

count(/*/div/p[string(.)])

这会生成所有具有非空字符串值的 p 元素的数量,这些元素是 div 的子元素,而 div 是 XML 文档顶部元素的子元素.

此外,如果非空"也意味着具有非空白字符串值:

count(/*/div/p[normalize-space(.)])

Please consider the following XML--

<div id="test">
    <p> Text sihdfaif</p>
    <p />
    <p> Text sihdfaif</p>
    <p />
    <p> Text sihdfaif</p>
    <p> Text sihdfaif</p>
    <p> Text sihdfaif</p>
</div>

Now, I want to obtain the number of p elements that have some text within them.. in this case, that value=5 (there are 2 'p' elements which are empty)

This is the XQuery that I came up with--

    let $claims_main := $doc//div[@id="test"]
        let $claims := $doc//div[@id="test"]/p
        let $n := count($claims)
        where $claims_main/p != '' 
        return $n

However the result that I get from the above is7, i.e. including the empty 'p' elements.

An alternative that I thought of, is using a for loop over all of the 'p' elements, but in that case how do I retrieve the total number of elements of the loop? If I use count in that case, then I simply get [1,1,1,1,1]- ie. count of each p element (since in the for loop the count would be for each of the 'p' elements, and not the div itself)...

解决方案

As the question asks specifically for "p elements that have some text within them", here is how to get the number of precisely such p elements:

count(/*/div/p[string(.)])

This produces the number of all p elements with non-empty string value, that are children of a div that is a child of the top element of the XML document.

In addition, if "non-empty" also means having non white-space-only string value:

count(/*/div/p[normalize-space(.)])

这篇关于xquery- 在单个父级中获取这些元素的计数,这些元素不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆