Is anyone able to explain why the two results are different, even though the node XML representation is exactly the same?
declare @t varchar(max) set @t = '<a><b><c/></b><d>eeee</d></a>'
declare @x xml set @x = cast(@t as xml)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('//*') T(N)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('/') T(N)
Result1:
Col1 Col2
<a><b><c /></b><d>eeee</d></a> a.
<b><c /></b> b.
<c /> c.
<d>eeee</d> d.
Result2:
Col1 Col2
<a><b><c /></b><d>eeee</d></a> .
Answer: (with the help from accepted answer from Mitch)
This query more clearly (relatively speaking) shows what is happening:
declare @t varchar(max) set @t = '<a><b><c/></b><d>eeee</d></a><x />'
declare @x xml set @x = cast(@t as xml)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('//*') T(N)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('/*') T(N)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('/') T(N)
Result1:
Col1 Col2
<a><b><c /></b><d>eeee</d></a> a.
<b><c /></b> b.
<c /> c.
<d>eeee</d> d.
Result2:
Col1 Col2
<a><b><c /></b><d>eeee</d></a> a.
<x /> x.
Result3:
Col1 Col2
<a><b><c /></b><d>eeee</d></a><x /> .
So in the original question, even though the XML in the results 1 and 2 are identical visually, they are "different".
- The first one is the XML-node starting at taking the (virtual) position of "root"
- The second one has a "virtual root" that is a "document" element that is not visually displayed.
'/'Selects from the root node'//'Selects nodes in the document from the current node that match the selection no matter where they are.Query 1 matches all root elements.
Query 2 matches the single element at the document root. The document root does not have a name.