[英]How to return last node having namespace in it using Xquery
我有這個文件,里面有命名空間,我正在嘗試編寫一個將返回的 Xquery,最后一個具有命名空間的節點,但無法找到返回命名空間節點的邏輯(PS:我是 Xquery 的新手)
XML 文件 -
<XML>
<SOAPMessage>
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<postRequestResponse xmlns="http://company.com">
<postRequestReturn>
<OnlineBRE xmlns="">
<Proccode>NUM</Proccode>
</OnlineBRE>
</postRequestReturn>
</postRequestResponse>
</soapenv:Body>
</soapenv:Envelope>
</SOAPMessage>
</XML>
我嘗試過查詢以返回具有確切字符串值的節點,但這沒有用。
您可以查找文檔中的所有元素//*
並測試謂詞過濾器中是否有namespace-uri()
,然后 select 具有namespace-uri()
的last()
元素。
let $doc :=
<XML>
<bk:BOOK xmlns:bk="urn:example.microsoft.com:BookInfo" xmlns:money="urn:Finance:Money">
<bk:TITLE>value1</bk:TITLE>
<ONLINEBRE />
<bk:PRICE money:currency="US Dollar">22.95</bk:PRICE>
</bk:BOOK>
</XML>
return ($doc//*[namespace-uri()])[last()]
根據您對 Mads Hansen 的回答的評論,我得出以下結論:
declare namespace array = "http://www.w3.org/2005/xpath-functions/array";
declare function local:ns-changed ($current as element(), $last-ns, $last-element) {
$current/element() ! (
let $child-ns := namespace-uri-from-QName(node-name(.))
return
if ( $child-ns = $last-ns )
then local:ns-changed(., $last-ns, $last-element)
else local:ns-changed(., $child-ns, .)
),
$last-element
};
let $root :=
<XML>
<SOAPMessage>
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<postRequestResponse xmlns="http://company.com">
<postRequestReturn>
<OnlineBRE xmlns="">
<Proccode>NUM</Proccode>
</OnlineBRE>
</postRequestReturn>
</postRequestResponse>
</soapenv:Body>
</soapenv:Envelope>
</SOAPMessage>
</XML>
let $initial-ns := namespace-uri-from-QName(node-name($root))
let $wanted := head(local:ns-changed($root, $initial-ns, $root))
return $wanted
我可能不漂亮且效率低下,也只在您提供的輸入上進行測試,但它可以滿足您的要求。
在這里您可以看到它的實際效果 https://xqueryfiddle.liberty-development.net/3Nzd8c9/1
目前它返回名稱空間更改的最后一個元素。 要返回節點名稱或值或其他內容,請修改最后一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.