Question

I have am using SQL SERVER 2008 R2. I have a stored proc that uses FOR XML to return results as XML. Here is what the stored proc looks like:

CREATE PROCEDURE [dbo].[myproc]
(
    @ID int,
)
AS
SET NOCOUNT ON
BEGIN 
SELECT 
    t1.FirstField
    t2.AnotherField
    t1.ThirdField
FROM table t1 
INNER JOIN table2 t2 ON t1.ID = t2.ID 
WHERE t1.id = @ID FOR XML RAW ('project'), ELEMENTS;
END

This works as expected and produces XML like this:

<project>
  <FirstField>First field data</FirstField>
  <AnotherField> Another field data</AnotherField>
  <ThirdField>Third field data</ThirdField>
</project>

Which is what I want. However my concern is that when there are special chars in the XML such as < and > will that not screw things up and make the XML malformed? Is there a way I can get around this? I can do some checks in the code that calls this stored proc to see if it is valid XML but by the time that happens wouldn't it be too late? If anyone could make some suggestions as to how I should approach this I would appreciate it. Thanks much.

Was it helpful?

Solution

SQL-Server will automatically encode your XML for you.

e.g.

SELECT  '<xml>Test</xml>'
FOR XML RAW ('Project'), ELEMENTS

returns

<Project>&lt;xml&gt;Test&lt;/xml&gt;</Project>

If you expect special characters you will need to decode your xml in whatever layer is requesting it from SQL-Server.

EDIT

If you do want to maintain the special characters within the fields you will need to use CDATA. This requires FOR XML EXPLICIT. The below would maintain the special characters and return the xml format you require.

SELECT  1 AS Tag,
        NULL AS Parent,
        FirstField AS [Project!1!FirstField!cdata],
        AnotherField AS [Project!1!AnotherField!Cdata],
        ThirdField AS [Project!1!ThirdField!cdata]
FROM    table t1 
        INNER JOIN table2 t2 
            ON t1.ID = t2.ID 
WHERE   t1.ID = @ID
FOR XML EXPLICIT
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top