3

How to change element name from Cust to Customer?

<Cust id="1">
  <Name>aaaaaaaaaa</Name>
  <Desc>bbbbbbbbbb</Desc>
</Cust>

When I'm using following statement

select @myXml.query('/node()[1]/node()') for xml raw('Customer')

sql removes attributes

<Customer>
  <Name>aaaaaaaaaa</Name>
  <Desc>bbbbbbbbbb</Desc>
</Customer>

2 Answers 2

1

Try this:

SELECT
    @myXml.value('(/Cust/@id)[1]', 'int') AS '@id',
    @myXml.query('/node()[1]/node()') 
FOR XML PATH('Customer')

Gives me an output of:

<Customer id="1">
  <Name>aaaaaaaaaa</Name>
  <Desc>bbbbbbbbbb</Desc>
</Customer>

With the FOR XML PATH, you can fairly easily "restore" that attribute that gets lost in the conversion.

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

Comments

1

You could use replace:

replace(replace(@YourXml, '<Cust id', '<Customer id)', '</Cust>', '</Customer>')

This is fairly safe, as < is not valid as data in XML, it would appear as &lt; or an ASCII or UNICODE sequence.

2 Comments

It's a non-grace method. Other ideas?
@chomik: XML modification support in SQL Server is entirely "non-grace". Consider doing this client site. :)

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.