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>

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

it's working but sorry i have not given complete structure of xml as there are some other elemts too at <stinfo> level which get removed after execution, i have updated xml in question
You simply add {info/teacher} before <Student> 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.
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

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.