1

I have the following XML.

<Root>
  <Child1>
    <SubChild1>some value</PartNumber>
  </Child1>
  <Child2>some data</Child2>
  <Child3>some data</Child3>
  <Child4>some data</Child4>
  <Child2>some data</Child2>
  <Child3>some data</Child3>
  <Child5>some data</Child5>
</Root>

I want to remove the duplicate nodes and return the XML in below format.

<Root>
  <Child1>
    <SubChild1>some value</PartNumber>
  </Child1>
  <Child2>some data</Child2>
  <Child3>some data</Child3>
  <Child4>some data</Child4>
  <Child5>some data</Child5>
</Root>

I tried below SQL query but it did not work.

SELECT @myXMLData.query('
    for $x in distinct-values(//*)[1]
        return
            (//*)[1]
')

I also tried distinct-values but it returns the values (without enclosing node attributes).

SELECT @XML.query('<Root>{ distinct-values(//*) }</Root>')

Any help with this please?

1 Answer 1

1
declare @x xml = N'<Root>
  <Child1>
    <SubChild1>some value</SubChild1>
  </Child1>
  <Child2>some data</Child2>
  <Child3>some data</Child3>
  <Child4>some data</Child4>
  <Child2>some data</Child2>
  <Child3>some data</Child3>
  <Child5>some data</Child5>
</Root>';

select node as '*'
from
(
select x.e.query('.') as node, row_number() over(partition by x.e.value('local-name(.)', 'nvarchar(100)') order by x.e) as nodenum
from @x.nodes('Root/*') as x(e)
) as src
where nodenum = 1
for xml path(''), root('Root');
Sign up to request clarification or add additional context in comments.

Comments

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.