我有一个如下格式的xml文档
<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的每个人的所有权,我编写了以下查询
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:如果我希望我的预期输出是‘
<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>‘查询应该是什么样子的?
发布于 2019-12-04 16:23:05
在查询中
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中使用):
doc('test.xml')//Ownership[SharesOwned > 150]至于您的edit1,您现在正在构建一棵树,它是原始树的修改版本。这在XSLT中要比在XQuery中容易得多(当然,如果您是在数据库上运行它,那么XQuery可能就是您所能得到的全部)。在XSLT 3.0中,它是:
<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更新,这是最容易实现的:语法是
delete nodes //Ownership[SharesOwned le 150]发布于 2019-12-04 13:46:06
这是你的xpath。如果你想得到Ownerships/Ownership的话。
//MyDoc/People/Person/Ownerships/Ownership[SharesOwned > 150]https://stackoverflow.com/questions/59169566
复制相似问题