SQLServer - Add XML Element ID and Key

Azmath Momin 61 Reputation points
2020-09-15T07:42:45.157+00:00

Dear Experts,

I have an XML Like below

<Root>
<node ID = "ABC" Name = "AAAA" />

</Root>

Now I want to add the XML to add two more fields to the same Node, the output should be required as below

<Root>
<node ID = "ABC" Name = "AAAA" Department = "ABCD" DEPTID = "1234"/>
</Root>

Developer technologies Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. MelissaMa-MSFT 24,221 Reputation points
    2020-09-15T09:26:17.817+00:00

    Hi @Azmath Momin ,

    Please refer below:

    DECLARE @xml xml =N'<Root>  
    <node ID = "ABC" Name = "AAAA" />  
    </Root> '  
      
    SET @xml.modify('               
    insert   
    (  
    attribute Department  {"ABCD" },  
    attribute DEPTID   {"1234" }  
    )  
    as last  
    into (/Root/node)[1]') ;     
      
    SELECT @xml  ;   
      
    --<Root><node Department="ABCD" ID="ABC" DEPTID="1234" Name="AAAA" /></Root>  
      
    --change the attributes in order  
    Declare @S varchar(max) = ''  
      
    Select @S = @S + concat(Item,'="',Value,'" ')  
     From (  
            Select Top 1000   
                   Item   = attr.value('local-name(.)','varchar(100)')  
                  ,Value  = attr.value('.','varchar(max)')   
             From  @XML.nodes('/Root/node') as A(r)  
             Cross Apply A.r.nodes('./@*') AS B(attr)  
             Order By attr.value('local-name(.)','varchar(100)')   
          ) A  
      
    Select convert(xml,'<Root><node '+@S+'/></Root>')  
      
    --<Root><node Department="ABCD" DEPTID="1234" ID="ABC" Name="AAAA" /></Root>  
    

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2020-09-15T08:37:10.113+00:00

    To affect the first <node>, try this example:

    declare @xml as xml =   
    '<Root>  
        <node ID="ABC" Name="AAAA" />  
    </Root>'  
      
    select @xml  
      
    set @xml.modify('insert ( attribute Department {"ABCD"}, attribute DEPTID {"1234"} ) into (/Root/node)[1]')  
      
    select @xml  
    

    It is possible to identify the target node by ID, or to deal with table's columns. Give some details if you need more features.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.