1

I have a scenario where I want to get the distinct nodes from XML.

So if I have this XML:

<person>
<age>
    <year value="2010"/>
    <month value="10"/>
    <day value="21"/>
</age>
<age>
    <year value="2011"/>
    <month value="11"/>
    <day value="4"/>
</age>
</person>

How could I retrieve in the results:

person
age
year
month
day

Is this possible? I was playing around with nodes.query and nodes.value, but I couldn't seem to figure out how to extract the actual node values?

Thanks,

S

4
  • I don't understand what you want here. You just want the name of the elements and don't care about the values? That's what it looks like from your desired results. Commented Oct 15, 2010 at 22:45
  • Yeah that is correct. I know it is strange, but I am hoping to use those to give me the ability to do node counts within the XML dynamically. So I can use that information to provide counts on each of the elements in teh XML and then use that in a query. Commented Oct 15, 2010 at 22:57
  • I am trying to figure out how I could build a dynamic call to count the nodes without have to actually build a dynamic query. So if I can expose the counts of each of the elements then I could use that in a where clause. Commented Oct 15, 2010 at 22:58
  • I edited the XML so I would have Person cnt = 1, Age Cnt = 2, Year Cnt = 2, Month Cnt = 2, and day Cnt = 2 then I could do something like where element = 'age' and get back 2 Commented Oct 15, 2010 at 23:00

1 Answer 1

4
DECLARE @person XML
SELECT @person = CAST('
    <person>
        <age>
            <year value="2010"/>
            <month value="10"/>
            <day value="21"/>
        </age>
        <age>
            <year value="2011"/>
            <month value="11"/>
            <day value="4"/>
        </age>
    </person>' AS XML)

;WITH nodeData AS (
    SELECT 
        node.value('local-name(.)', 'NVARCHAR(MAX)') AS nodeName,
        node.query('.') AS nodeInstance
    FROM @person.nodes('/*') a(node)
    UNION ALL
    SELECT 
        node.value('local-name(.)', 'NVARCHAR(MAX)'),
        node.query('.')
    FROM nodeData
    CROSS APPLY nodeInstance.nodes('/*/*') b(node)
)
SELECT nodeName, COUNT(nodeName) AS nodeCount FROM nodeData
GROUP BY nodeName 
ORDER BY nodeCount DESC
Sign up to request clarification or add additional context in comments.

1 Comment

This is money because now I don't have to make th

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.