1

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.

1 Answer 1

2

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)     
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for fast reply. your code gives me 9 records, is it possible to get only first 3 records? bcz, here i do not consider the parent, i want only child elements values without duplicates. is it possible via sql script?

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.