[英]How to retrieve parent node with child node that matching certain criteria using xquery?
[英]How to retrieve parent node using XQuery?
我正在使用XML和XQuerie。 我通常使用相对于父节点的XPath表达式来检索其子节点。 但是,如果我有一个子节点,我不知道如何做相反的意思,我如何检索其父节点。
<node id="50>
<childnode1 childid="51" />
<childnode2 childid="52" />
</node>
如果我有节点<childnode1 childid="51" />
,我该如何检索其父<node id="50>
: <node id="50>
简短回答 :
..
这将选择当前(上下文)节点的父节点。
更长,更一般的答案 :
//node()[childnode1/@childid="51"]
这将选择文档中具有名为childnode1
的子元素的任何节点,该子元素具有childid
,其值为“51”。
应该尽量避免使用包含//
缩写的表达式,因为这可能效率很低。 仅在事先不知道XML文档的结构时才使用'//'。
最佳答案 :
ExpressionSelectingTheChildNode/..
你使用..
来获取父母,像这样:
../childnode1
所以如果你有一些像这样的XML文档:
<a id="1">
<b id="2">
<c id="3">
<d id="4"/>
</c>
<c id="5"/>
<c id="6">
<d id="7"/>
</c>
</b>
</a>
那么XQuery
//../d[@id = "4"]
将返回id
为3
的c
节点。
以下是获取父节点(..)的更复杂示例。
问)找出一个国家最受欢迎的语言是另一个国家最不受欢迎的语言,并且这两个国家都列出了多种语言。 https://prod-c2g.s3.amazonaws.com/db/Winter2013/files/countries.xml
一种)
for $b in doc("countries.xml")/countries/country/language
for $c in doc("countries.xml")/countries/country/language
where $b/../@name != $c/../@name
and data($b) = data($c)
and count($b/../language) > 1
and count($c/../language) > 1
and $b/@percentage = max($b/../language/@percentage)
and $c/@percentage = min($c/../language/@percentage)
return
<LangPair language="{data($b)}">
<MostPopular>{data($b/../@name)}</MostPopular>
<LeastPopular>{data($c/../@name)}</LeastPopular>
</LangPair>
或者,您也可以使用fn:root()
Xquery函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.