How to replace all illegal XML chars when casting to XML

Naomi Nosonovsky 8,191 Reputation points
2025-02-27T18:10:56.1533333+00:00

Hi,

What is the proper way to cast varchar value to XML which may contain illegal XML characters? Can you please explain with CDATA or should it be complex replace command?

Thanks in advance.

SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
130 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Erland Sommarskog 117.8K Reputation points MVP
    2025-02-27T22:24:45.4366667+00:00

    The whole thing just looks wrong. Why would you cast an individual Address column to XML? That seems funny. And why would you replace a NULL address with a string like that? Yes, if you have in an XML document, it will be a space when you extract it. But your colleague does not have any XML at this point.

    I think the snippet should be:

    SELECT COALESCE(z.Address1, ' ') AS "@Address1",
           COALESCE(z.Address2, ' ') AS "@Address2",
           COALESCE(z.City, ' ') AS "@City",
           COALESCE(z.State, ' ') AS "@State",
    	   COALESCE(z.PostalCode, ' ')AS "@PostalCode",
    	   COALESCE(z.County, ' ') AS "@County"
    FOR XML PATH('Address'), TYPE
    

    I've added @ before the column names to that the columns become attributes and not elements.

    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.