2012-12-21 70 views
0

在XQuery中使用計算元素構造,我該如何與computed element constructor混合使用XML來從一個變量設置一個節點的標籤。的XQuery - 文本

我試圖做這種方式,但沒有運氣:

if ($x eq "something") then 
    <cp:value> 
     {element {fn:string-join(("if:GICS", $cp/@id), "")} {""}} 
    </cp:value> 

的預期結果是:

<cp:value> 
    <if:GICS1234 /> 
</cp:value> 

回答

1

的元素構造的元素名稱的一部分需要一個xs:QName生產要素名稱。如果提供了一個字符串,它會將它強制轉換爲QName,就像您調用了`xs:QName('my-element-name')一樣。

因此,你必須遵守所有,如果你在那裏有一個明確的xs:QName()構造函數,你會遵守規則。這意味着如果您使用的是名稱空間前綴(如if:),則必須可以在靜態上下文中解析該名稱空間。

你可以做最簡單的事情是簡單地宣佈你if:命名空間在你的序言(如想必你宣佈你的cp:命名空間):

declare namespace if = "http://example.org/if"; 
element {fn:concat('if:GICS','1234') } {} 

(: usually produces <if:GICS1234 xmlns:if="http://example.org/if"/> :) 

如果你不想這樣做,你可以使用fn:QName()函數和if:的完整名稱空間明確構建一個QName。 (注意:*fn:*QName不同於*xs:*QName!)

element {fn:QName('http://example.org/if', fn:concat('GICS', '1234'))} {} 

(: usually produces <GICS1234 xmlns="http://www.example.org/if"/> :) 

如果你想控制使用的前綴,「如果:」您可以在第二個參數:

element {fn:QName('http://example.org/if', fn:concat('if:GICS','1234'))} {} 

(: produces <if:GICS1234 xmlns:if="http://example.org/if"/> :) 

注意,正是什麼您在xml輸出中獲得的前綴可能因xquery處理器和您生產的xml結構而異,但您將始終獲得等效的XML Infoset。

0

您不能直接在字符串中的命名空間前綴。您需要從命名空間url創建一個包含命名空間的QName。

使用類似

if ($x eq "something") then 
    <cp:value> 
    {element {fn:QName("if namespace url", fn:string-join(("if:GICS", $cp/@id), ""))} {""}} 
    </cp:value> 

而且你可以一樣好使用CONCAT代替字符串連接

if ($x eq "something") then 
    <cp:value> 
    {element {fn:QName("if namespace url", fn:concat(("if:GICS", $cp/@id)))} {""}} 
    </cp:value>