Ask questions via twitter! Message any question to @answers on twitter. We'll publish the question and send you a reply each time there's a new answer.
Next Question

Question

 
M$4 May 08, 2009 09:35 PM

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.
Interesting Question?  Yes (0)   No (0)   
Email to a friend | RSS
 
 

 
   No Best Answer Selected, Tip Refunded
 
 


Answers (2)

Sort By
 
May 13, 2009 10:23 AM
Hi,

Can this help:

http://www.mssqltips.com/tip.asp?tip=1609

Helpful Answer?  (0)   (0)    Tip onek for this answer
Permalink | Report
   Reply  
 
 
 
June 26, 2009 08:10 PM
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

Helpful Answer?  (1)   (0)   

Helpful: darth continent

Tip northlight_john for this answer
Permalink | Report
   Reply  
 
 
Buy Mahalo Dollars with Credit Card or PayPal

Top Members

This Week All Time
  • buddawiggi
    buddawiggi
    2nd Degree Black Belt
    27543 Points
    M$789.91 Earned
  • opher
    opher
    Purple Belt
    4443 Points
    M$196.22 Earned
  • annelisle
    annelisle
    Purple Belt
    2997 Points
    M$91.22 Earned
   See All
 

Most Popular Tags

mahalo(1614)
iphone(465)
music(459)
google(357)
food(321)
online(295)
beer(279)
money(262)
movies(255)
apple(251)
aotd(235)
health(219)
video(207)
dog(205)
free(204)
   See All
 

Categories

Welcome New Members


 
 
Mahalo Dollars are the currency of Mahalo Answers.

Each Mahalo Dollar costs $1.

Once you earn more than 40 Mahalo Dollars, you can request to be paid via PayPal. Each Mahalo Dollar is currently worth $0.75 when paid out via PayPal. Learn More

 
 

Please log in to use this function.