Gomathipriya
Gomathipriya

Reputation: 945

get child element value using sql server

from the following code how to get the child element value only once. i.e when i parse from root-> parent-> child -> i need to loop for child element tag to get all child element value then parse to end of parent and end of root. i do not want to go to next parent -> next child.

<root>
   <parent> 
        <name>g</name>
        <child>child1</child>
        <child>child2</child>
        <child>child3</child>
     </parent>

   <parent> 
        <name>s</name>
        <age>23</age>
        <child>child1</child>
        <child>child2</child>
        <child>child3</child>
     </parent>


   <parent> 
        <name>t</name>
        <child>child1</child>
        <child>child2</child>
        <child>child3</child>
     </parent>

Here, I need to get the child element values only once without parsing whole file. while i write xml file i know these elements values are same for all the parent node. in this scenario, how to get child1,child2,child3 from the above file.

Upvotes: 1

Views: 4570

Answers (1)

marc_s
marc_s

Reputation: 754268

Try this:

DECLARE @XML XML = '<root>
   <parent> 
        <name>g</name>
        <child>child1</child>
        <child>child2</child>
        <child>child3</child>
     </parent>

   <parent> 
        <name>s</name>
        <age>23</age>
        <child>child1</child>
        <child>child2</child>
        <child>child3</child>
     </parent>


   <parent> 
        <name>t</name>
        <child>child1</child>
        <child>child2</child>
        <child>child3</child>
     </parent>
</root>'

SELECT
    ChildNodeName = XC.value('(.)[1]', 'varchar(50)'),
    ParentName = XC.value('(../name)[1]', 'varchar(50)')
FROM 
@XML.nodes('/root/parent/child') AS XT(XC)     

Basically, get a list of all <child> nodes using .nodes() and then iterate over these child nodes - output what you need. To reach the "parent" node for each <child> node, use the ../name XPath expression.

Update: if you want only the distinct child data - use this query:

SELECT
    DISTINCT ChildNodeName = XC.value('(.)[1]', 'varchar(50)')
FROM 
    @XML.nodes('/root/parent/child') AS XT(XC)     

Upvotes: 2

Related Questions