[英]XPath for xquery to apply where clause on each element
我有以下格式的 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
在此之后,我預計該查詢將僅返回公司 ID 為 2 的公司 ID 為 2 的所有權,公司 ID 為 4 的公司 2 的所有權,但它返回了所有 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>
''' 查詢應該是什么樣的?
在您的查詢中
for $person in doc('test.xml')//People/Person
let $ownership := $person/Ownerships/Ownership
where $ownership/SharesOwned > 150
return $ownership
你的錯誤是在第二個子句中使用let
而不是for
。 這將變量$ownership
綁定到給定人員的所有權集合,如果該集合中的任何項目滿足謂詞,則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]
這是你的xpath
。 如果你想獲得Ownerships/Ownership
。
//MyDoc/People/Person/Ownerships/Ownership[SharesOwned > 150]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.