首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在每个元素上应用where子句的XPath

在每个元素上应用where子句的XPath
EN

Stack Overflow用户
提问于 2019-12-04 13:40:37
回答 2查看 88关注 0票数 0

我有一个如下格式的xml文档

代码语言:javascript
复制
<MyDoc>
   <People>
     <Person>
        <Id id = 1>
        <Ownerships>
           <Ownership>
               <Owns companyId = 2/>
               <SharesOwned> 200 </SharesOwned>
          </Ownership>
          <Ownership>
               <Owns companyId = 3/>
               <SharesOwned> 100 </SharesOwned>
          </Ownership> 
     <Ownerships>
   </Person> 
   <Person>
        <Id id = 2>
        <Ownerships>
           <Ownership>
               <Owns companyId = 4/>
               <SharesOwned> 400 </SharesOwned>
          </Ownership>
          <Ownership>
               <Owns companyId = 3/>
               <SharesOwned> 20 </SharesOwned>
          </Ownership> 
     <Ownerships>
   </Person> 
 </People>
</MyDoc>

对于我想要查询拥有的股份大于150的每个人的所有权,我编写了以下查询

代码语言:javascript
复制
for $person in doc('test.xml')//People/Person
let $ownership := $person/Ownerships/Ownership
where $ownership/SharesOwned > 150
return $ownership

在此之后,我原以为查询将只返回person 1的公司id为2和person 2的company id为4的所有权,但它返回所有4个所有权。

文档结构是否有问题,或者我应该如何编写查询以获得所需的结果。

编辑1:如果我希望我的预期输出是‘

代码语言:javascript
复制
<People>
     <Person>
        <Id id = 1>
        <Ownerships>
           <Ownership>
               <Owns companyId = 2/>
               <SharesOwned> 200 </SharesOwned>
          </Ownership>
    <Ownerships>
   </Person> 
   <Person>
        <Id id = 2>
        <Ownerships>
           <Ownership>
               <Owns companyId = 4/>
               <SharesOwned> 400 </SharesOwned>
          </Ownership>
     <Ownerships>
   </Person> 
 </People>

‘查询应该是什么样子的?

EN

回答 2

Stack Overflow用户

发布于 2019-12-04 16:23:05

在查询中

代码语言:javascript
复制
for $person in doc('test.xml')//People/Person
let $ownership := $person/Ownerships/Ownership
where $ownership/SharesOwned > 150
return $ownership

您的错误是在第二个子句中使用let,而不是for。这会将变量$ownership绑定到给定person的所有权集合,如果该集合中的任何项满足谓词,则where子句将选择该$ownership

就我个人而言,我发现像这样的查询的XPath公式要简单得多,也更具可读性(当然,它也可以在XQuery中使用):

代码语言:javascript
复制
doc('test.xml')//Ownership[SharesOwned > 150]

至于您的edit1,您现在正在构建一棵树,它是原始树的修改版本。这在XSLT中要比在XQuery中容易得多(当然,如果您是在数据库上运行它,那么XQuery可能就是您所能得到的全部)。在XSLT 3.0中,它是:

代码语言:javascript
复制
<xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:template match="Ownership[SharesOwned le 150]"/>
</xsl:transform>

在XQuery中,如果可以使用XQuery更新,这是最容易实现的:语法是

代码语言:javascript
复制
delete nodes //Ownership[SharesOwned le 150]
票数 4
EN

Stack Overflow用户

发布于 2019-12-04 13:46:06

这是你的xpath。如果你想得到Ownerships/Ownership的话。

代码语言:javascript
复制
//MyDoc/People/Person/Ownerships/Ownership[SharesOwned > 150]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59169566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档