Could anyone tell me how I could select values from the following xml:
I would like to get rows as follows:
Col1: key, Col2: key, Col3: value
1 1 value
1 2 value2
1 3 value3
2 4 value4
2 5 value5
2 6 value6
Here is the xml:
<root>
<item>
<key>1</key>
<value>
<params>
<item>
<key>1</key>
<value>value</value>
</item>
<item>
<key>2</key>
<value>value2</value>
</item>
<item>
<key>3</key>
<value>value3</value>
</item>
</params>
</value>
</item>
<item>
<key>2</key>
<value>
<params>
<item>
<key>4</key>
<value>value4</value>
</item>
<item>
<key>5</key>
<value>value5</value>
</item>
<item>
<key>6</key>
<value>value6</value>
</item>
</params>
</value>
</item>
</root>
Best Answer
Assuming you have this XML in a T-SQL variable - then you could use this snippet of code:
This gives me an output of:
The approach is the following:
grab the list of
<item>
nodes under<root>
as your first "list of XML nodes" with the first.nodes()
XQuery method, and extract the value of the<key>
XML element in that XML fragment intoKey1
grab the "nested" list of XML nodes inside that XML fragment, using the
value/params/item
XPath, to get the child rows - and extract the values from<key>
and<value>
from those nested child XML fragments intoKey2
andItemValue