views:

35

answers:

1

Similiar to question: http://stackoverflow.com/questions/2266132/how-can-i-get-a-list-of-element-names-from-an-xml-value-in-sql-server

How would I also get the values for the list of elements.

For example:

<Root>
<A>a1</A>
<B>b1</B>
<C>c1</C>
</Root>

Would return
Element   |  Value
A         |    a1
B         |    b1
C         |    c1

Sorry for the confusion, I didn't know how to do the formatting. I just want the element name and the value and do not care about the hierarchy.

Thanks,

+1  A: 
declare @xml xml
set @xml = '<Root><A>a1</A><B>b1</B><C>c1</C><D><E>e1</E></D><F>f1<G>g1</G></F></Root>'

select
    element.value('fn:local-name(.)', 'varchar(max)') as Element,
    element.value('text()[1]', 'varchar(max)') as Value
from @xml.nodes('/*//*') as nodes(element)

OUTPUT:

Element  Value
-------- ----------
A        a1
B        b1
C        c1
D        NULL
E        e1
F        f1
G        g1

(7 row(s) affected)
Daniel Renshaw
Sorry for the formatting problem I had. I just want the Element Name and it's value without the hierarchy.
Kevin
I've edited my answer. This is a much simpler problem!
Daniel Renshaw
+1, works for me. I don't like editing other people's answers, but your answer is correct (and the code actually runs). If you add the output like this when you have a sample that runs, you'll show people that this isn't just code off the top of your head, but that it actually runs. Which will result in possibly more up votes.
KM
thanks KM, will do
Daniel Renshaw