Use SQL Server 2005 XML APIs to normalize an XML fragment -


i have (untyped) xml being stored in sql server 2005 need transform normalized structure. structure of document looks so:

<wrapper>  <parent />  <node />  <node />  <node />   <parent />  <node />  <node />  <node /> <wrapper>  

i want transform this:

<wrapper>  <parent>   <node />   <node />   <node />  </parent>  <parent>   <node />   <node />   <node />  </parent> <wrapper>  

i can select xml out relational structure if need to, put problem there no attributes linking parent , child nodes together, order becomes issue when using set-based operations. how can use .nodes()/.value()/other sql server xml apis transform data? transformation needs run part of batch sql script extracting tool/language not reasonable option me.

actually - following code works (grouping here may isn't optimal, anyway):

declare @xml xml = '     <wrapper>      <parent id="1" />      <node id="1" />      <node id="2" />      <node id="3" />       <parent id="2" />      <node id="4" />      <node id="5" />      <node id="6" />     </wrapper>  '  ;with px (     select row_number() on (order (select 1)) rownumber         ,t.v.value('@id', 'int') id         ,t.v.value('local-name(.)', 'nvarchar(max)') tagname     @xml.nodes('//wrapper/*') t(v) ) select p.id [@id],     (         select n.id id         px n         n.tagname = 'node'             , n.rownumber > p.rownumber             , not exists             (                 select null                 px np                 np.tagname = 'parent'                     , np.rownumber > p.rownumber                     , np.rownumber < n.rownumber             )         order n.rownumber         xml raw('node'), type     ) px p p.tagname = 'parent' order p.rownumber xml path('parent'), root('wrapper')

but don't recommend use it. see here: http://msdn.microsoft.com/en-us/library/ms172038%28v=sql.90%29.aspx:

in sqlxml 4.0, document order not determined
i'm not sure can rely on order of tags inside wrapper (and code above more fun practical use).


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -