I was just surfing net and came across a very good function "local-name". When i searched for its defination in Books Online I found it as a function which "Returns the local part of the name of $arg as an xs:string". It means that whatever the parameter is passed to it, it provides the node name of it. If the argument is not specifed it uses the context mode. Context mode allows to search for a particular pattern or word.
Say for example we have an xml as:
DECLARE @Data XML
SET @Data = '
<root>
<root1>
<root2>
<root3>
<notes>Notes under root3</notes>
</root3>
<notes>Notes under root2</notes>
</root2>
<notes>Notes under root1</notes>
</root1>
<notes>Notes under root</notes>
</root>'
Now, looking the xml say we want the inner xml nodes and data for the root under "root2". I think its tough using simple xquery. But local-name has made our problem so easy. By using the context mode of local-name it can be easily done.
Context mode can be used by specifying square brackets and the search word.
SELECT @Data.query ( '//*[local-name()="root2"]')
The output is:
<root2>
<root3>
<notes>Notes under root3</notes>
</root3>
<notes>Notes under root2</notes>
</root2>
The syntax is ( '//*[local-name()="nodename"]')
"//*" traverses the whole xml. It could even be used to iterate through the whole xml to have the parent node and chile node name just like as we were getting in OpenXML.
Try this query:
SELECT e.value('local-name(..)[1]', 'VARCHAR(MAX)') AS ParentNodeName,
e.value('local-name(.)[1]', 'VARCHAR(MAX)') AS ChildNodeName
FROM @data.nodes('//*') AS T(e)
Output:

I guess you might be now able to use local-name well wherever such type of situations arise. I remember we have one Challenge of Parent child relationship, but that was regarding the data. If anytime the node name has to be arranged in the same form it could be done by using local-name.
Tags: XML, local-name, XQuery,