Reputation: 28
I got the following XML:
<Node attr1="value1" attr2="value2">
<SubNode SubAttr1="subValue1" subAttr2="subValue2" />
</Node>
I would like to know if there is a way to do a XQuery expression to return only the <Node>
element.
<Node attr1="value1" attr2="value2">
<Node>
Upvotes: 0
Views: 816
Reputation: 38682
I'm sorry you're out of luck here for a general solution – if you're bound to use Microsoft SQL Server, which does not offer computed element constructors with names that are computed on the fly (like @dirkk is using).
When you know that this element is always called "Node", you can do following (using a fixed node name):
element Node { /Node/@* }
If you also want to include (direct) text children:
element Node { /Node/@*, /Node/text() }
If you need to support arbitrary element names: you cannot do this with XQuery in SQL Server.
Upvotes: 2
Reputation: 6218
You can write a function to do this:
declare function local:strip-children($e as element()*) as element()* {
element {node-name($e)} {$e/@*}
};
local:strip-children(/Node)
Of course you can also do this without a function like so:
element {node-name(/node)} {/Node/@*}
So you simply inline the code from the function. However, in my opinion the function approach is much more reusable.
Upvotes: 0