1

I have an xml column in my table like following:

   <info>
      <teacher>     
            <name>John</name>   
      </teacher>
      <StInfo>
        <name>William</name>    
        <address>India</address>    
      </StInfo>
    </info>

I have to just update to

 <info>
          <teacher>     
                <name>John</name>   
          </teacher>
          <Student>
            <name>William</name>    
            <address>India</address>    
          </Student>
        </info>
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
donstack
  • 2,557
  • 3
  • 29
  • 44

2 Answers2

4

I've built an example for you in SQL Server using your data:

DECLARE @StackExample TABLE (
     Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT(NEWID())
    ,XmlColumn XML
)

INSERT INTO @StackExample(XmlColumn) VALUES('<info>
  <StInfo>
    <name>William</name>    
    <address>India</address>    
  </StInfo>
</info>')


UPDATE T
SET XmlColumn = XmlColumn.query('<info>
  <Student>
  {info/StInfo/*}
  </Student>
</info>')
FROM @StackExample t

SELECT * FROM @StackExample

I hope this can help

Roberto Conte Rosito
  • 2,080
  • 12
  • 22
  • it's working but sorry i have not given complete structure of xml as there are some other elemts too at level which get removed after execution, i have updated xml in question – donstack Nov 13 '13 at 18:05
  • 1
    You simply add {info/teacher} before tag in the update statement and it's done . Sorry but I can't test it, but i want to sent you a fast response to give you the change to try. – Roberto Conte Rosito Nov 13 '13 at 18:28
0

As far as I know, there's no way to modify xml element names with SQL DML. You can replace it after converting to varchar:

update Table1 set
    data = cast(
      replace(
        replace(
          cast(data as nvarchar(max)),
        '</StInfo>', '</Student>'
        ),
      '<StInfo>', '<Student>'
      )
    as xml)

Or you can reconstruct your xml using XQuery:

update Table1 set
    data = data.query('<info>{
                for $i in info/StInfo
                return element Student {$i/*}
                }</info>'
    )

These appoaches will work even for multiple elements.

sql fiddle demo

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197