darth continent's Avatar
darth continent 4
40 Asked
593 Answered
160 Best
0
No one has voted on this question yet :(
3 years ago

XML transformation using OPENXML in SQL 2005?

I have a SQL 2005 xml variable, @xml, which I need to transform from this:

@xml = '< RB >< RI Type="Sausages" Term="12" DI="11" PO="0" />< PromoInfo />< /RB >'

...to this...

@xml = '< RB >< RI >< Type >Sausages< /Type >< Term >12 < /Term >< DI >11 < PO >0 < /PO >< /RI >< /RB >'

How can I do this using either OPENXML or some other means in SQL 2005? Basically I'm needing to "unbox" the attributes in the first @xml and create separate nodes out of each of them.
Tip for best answer: M$4.00
Separate topics with commas, or by pressing return. Use the delete or backspace key to edit or remove existing topics.

You can leave an optional "tip" with Mahalo's virtual currency, Mahalo Dollars. If you are asking a difficult question that might require some research, or if you'd like a wide variety of feedback, a higher tip often leads to more answers to your question.

M$

What is Your Answer?

0
0
0

2 Answers

1
northlight_john's Avatar
northlight_john | 2 years, 11 months ago
3
Hi,

This T-SQL will do what you asked for, but it would need to be modified if you have more than one element to work with. I couldn't tell from your example exactly what the schema for the incoming XML would be like.

DECLARE @xml XML
DECLARE @xml_new XML
DECLARE @idoc INT

-- your sample xml
SET @xml = ''

--create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @xml

-- USE OPENXML to SELECT attributes out of @xml, then use "FOR XML" to create new xml
SET @xml_new = (
SELECT Type, Term, DI, PO
FROM OPENXML (@idoc, '/RB/RI',1)
WITH (
Type VARCHAR(16)
,Term INT
,DI INT
,PO INT
)
FOR XML PATH('RI')
)

-- done with XML document
EXEC sp_xml_removedocument @idoc

You can leave an optional "tip" with Mahalo's virtual currency, Mahalo Dollars. If you are asking a difficult question that might require some research, or if you'd like a wide variety of feedback, a higher tip often leads to more answers to your question.

M$

Report Abuse

Post Reply Cancel
0
onek's Avatar
onek | 3 years ago
3

You can leave an optional "tip" with Mahalo's virtual currency, Mahalo Dollars. If you are asking a difficult question that might require some research, or if you'd like a wide variety of feedback, a higher tip often leads to more answers to your question.

M$

Report Abuse

Post Reply Cancel

Learn something new with our FREE educational apps!

Private lessons in the comfort of your own home. Get back in shape or finally pick up a guitar with our great experts guiding you the whole way!
Learn Guitar
Learn Hip Hop
Learn Pilates