in

SQLServerCentral.com

The largest free SQL Server community.

Pro SQL Server XML

SQL Server + XML Development Tutorials, Tips, and Tricks

Grabbing Node Names and Values

I got a question the other day about grabbing node names and values from an XML document. The person asking was using string parsing with the SUBSTRING function to split out names from content based on '>' characters in the XML string. Not a fullproof solution, to be sure, but quick and easy based on his predictable XML data.  So the question then becomes is there an XML-based method to grab this information? 

DECLARE @x xml;
SET @x = N'<?xml version = "1.0"?>
<root>
  <person>
    <name>
      <first-name>Joe</first-name>
      <last-name>Johnson</last-name>
    </name>
    <name>
      <first-name>Lennox</first-name>
      <last-name>Lewis</last-name>
    </name>
    <name>
      <first-name>Louie</first-name>
      <last-name>McDougal</last-name>
    </name>
  </person>
</root>'
;

SELECT
node.query('fn:local-name(.)') AS NodeName, node.query('./text()') AS NodeValue
FROM @x.nodes(N'//*') T(node);

The fn:local-name() function retrieves the local name portion of XML node names, and the text() node test retrieves the node text, as shown below.

Result of fn:local-name() query

Add to Technorati Favorites 

Published Mar 07 2008, 11:51 AM by Mike C
Filed under: , ,

Comments

No Comments

About Mike C

Michael Coles is a SQL Server consultant with over a dozen years' experience in SQL database design, T-SQL development, and client-server application programming. He has consulted in a wide range of industries, including the insurance, finance, retail, and manufacturing sectors, among others. He has published dozens of highly rated technical articles online and in print magazines including SQL Server Central, ASP Today, and SQL Server Standard magazine. He is the author of the books Pro SQL Server 2008 XML, Pro T-SQL 2005 Programmer's Guide, and a contributor to Accelerated SQL Server 2008. Current projects include writing the Pro T-SQL 2008 Programmer's Guide.
Copyright Red Gate Software
Powered by Community Server (Commercial Edition), by Telligent Systems