Tuesday, April 9, 2013

Listing XML Elements and attribute names with XqueryPaths

Been a while since I made a post. I have been quite busy with the new job and resurrected a piece of code that I thought might be useful to someone else. The following code will list the Name of each entity in the xml doc and the compatible X-Query path.

DECLARE @xml XML
SET @xml ='<?xml version="1.0"?>
<dtsconfiguration>
 <dtsconfigurationheading>
  <dtsconfigurationfileinfo GeneratedBy="Generic" GeneratedFromPackageName="Generic" GeneratedFromPackageID="{AA722E45-EE85-4C19-9BFA-8776E1A7463B}" GeneratedDate="7/31/2019 11:27:59 AM"/>
 </DTSConfigurationHeading>
 <configuration ConfiguredType="Property" Path="\Package.Connections[Test].Properties[ConnectionString]" ValueType="String">
  <configuredvalue>Data Source=Local;Initial Catalog=Tester;Provider=SQLNCLI10.1;Integrated Security=SSPI;Auto Translate=False;</ConfiguredValue>
 </Configuration>
 <configuration ConfiguredType="Property" Path="\Package.Connections[Test].Properties[ServerName]" ValueType="String">
  <configuredvalue>local</ConfiguredValue>
 </Configuration>
</DTSConfiguration>'
;
WITH CTE
AS (
 SELECT node.value('fn:local-name(.)', 'varchar(max)') NAME
  ,'/' + node.value('fn:local-name(.)', 'varchar(max)') Path
  ,node.query('*') Children
  ,Convert(varchar(max),'') Parent
  ,0 as depth
  FROM @xml.nodes('*') AS Root(node)
 
 UNION ALL
 
 SELECT node.value('fn:local-name(.)', 'varchar(max)') NAME
  ,Parent+'/' +cte.NAME + '/' + node.value('fn:local-name(.)', 'varchar(max)') Path
  ,node.query('*') Children
  ,Parent + '/'+ NAME  Parent
  ,depth +1
 FROM cte
 CROSS APPLY cte.children.nodes('*') AS Child(node)
 
 UNION ALL
 
 SELECT '@'+node.value('fn:local-name(.)', 'varchar(max)') NAME
  ,Parent+'/' +CTE.NAME + '/'+node.value('fn:local-name(../.)', 'varchar(max)')+  '/@' + node.value('fn:local-name(.)', 'varchar(max)') Path
  ,'' Children
  ,Parent + '/'+ NAME Parent
  ,depth +1
 FROM cte
 CROSS APPLY cte.children.nodes('/*/@*') AS Child(node)
 )
SELECT *
FROM cte
order by depth
 
 

No comments:

Post a Comment