Share via

Remove xml encoding from string

kasim mohamed 581 Reputation points
2021-06-19T15:49:26.283+00:00

Hi,

I have a sting like below

declare @XML nvarchar(max) = '<?xml version="1.0" encoding="US-ASCII"?><Rem.Ace xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> </Rem.Ace>';

i want to remove xml encoding details and need result as below string
<Rem.Ace xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> </Rem.Ace>;

Note: the encoding will change dynamically sometimes it would be utf-8 or utf-16

Thanks

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Viorel 127K Reputation points
2021-06-19T16:30:28.21+00:00

Maybe the string operations are suitable:

if @xml like N'<?xml%' 
   set @xml = ltrim(substring(@xml, charindex(N'?>', @xml) + 2, len(@xml)))

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 27,196 Reputation points
    2021-06-20T02:55:14.59+00:00

    Hi @kasim mohamed ,

    Very similar to Viorel's solution, just shorter.

    SQL

    DECLARE @xml NVARCHAR(MAX) =  
    N'<?xml version="1.0" encoding="US-ASCII"?>  
    <Rem.Ace xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">;</Rem.Ace>';  
      
    SET @xml = STUFF(@xml, 1, CHARINDEX('?>', @xml) + 1, '');  
      
    -- test  
    SELECT @xml;  
    

    Was this answer helpful?

    0 comments No comments

Your answer

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