带有CDATA的SQL Server XML输出

时间:2009-09-15 20:08:02

标签: sql-server xml cdata

有没有办法让SQL Server XML返回使用CDATA?我有SQL Server返回的XML,如下所示:

<locations>
    <site id="124">
        <sitename>Texas A &amp; M</sitename>
    </site>
</locations>

当我需要这个时:

<locations>
    <site id="124">
        <sitename><![CDATA[Texas A & M]]></sitename>
    </site>
</locations>

3 个答案:

答案 0 :(得分:15)

查看FOR XML EXPLICIT(参数指令)的选项。它提供了更大程度的控制,您还可以指定CDATA。这是a good tutorial

从该教程中添加了代码:

declare @agent table
(    
    AgentID int,
    Fname varchar(5),
    SSN varchar(11)
)

insert into @agent
select 1, 'Vimal', '123-23-4521' union all
select 2, 'Jacob', '321-52-4562' union all
select 3, 'Tom', '252-52-4563'

SELECT
    1 AS Tag,
    NULL AS Parent,
    NULL AS 'Agents!1!',
    NULL AS 'Agent!2!AgentID',
    NULL AS 'Agent!2!Fname!Element',
    NULL AS 'Agent!2!SSN!cdata'
UNION ALL
SELECT
    2 AS Tag,
    1 AS Parent,
    NULL, 
    AgentID,
    Fname,
    SSN
FROM @agent
FOR XML EXPLICIT

答案 1 :(得分:0)

正如乔尔在上面的评论中提到的那样,这两种形式应该完全相同。但是,如果确实需要CDATA表格,那么你可以编写一个后处理器,它将第一个表格作为输入,并使用CDATA输出第二个表格。

执行此操作时,后处理器将以第一种形式取消编码 XML转义数据,并使用CDATA兼容方法对其进行重新编码。有关CDATA转义的注意事项,请参阅问题Is there a way to escape a CDATA end token in xml?

答案 2 :(得分:0)

以下是我获取CDATA的一个例子:

DECLARE @GlobalDateFormat varchar(32)
SET @GlobalDateFormat = 'MM/dd/yyyy hh:mm tt'

DECLARE @xml XML

SET @xml = 
(
    SELECT
            SegmentId         = ISNULL(SegmentId,0)
        ,   DocumentId        = ISNULL(DocumentId,0)
        ,   Title             = CAST(Core.dbo.fCharFormat('xmlCDATA',Title,DEFAULT,'') AS xml)
        ,   DocumentShortName = CAST(Core.dbo.fCharFormat('xmlCDATA',DocumentShortName,DEFAULT,'') AS xml)
        ,   [FileName]        = CAST(Core.dbo.fCharFormat('xmlCDATA',[FileName],DEFAULT,'') AS xml)
        ,   [Path]            = CAST(Core.dbo.fCharFormat('xmlCDATA',[Path],DEFAULT,'') AS xml)
        ,   CreateDate        = ISNULL(Core.dbo.fDateFormat(@GlobalDateFormat,CreateDate),Core.dbo.fDateFormat(@GlobalDateFormat,GETDATE()))
        ,   ModificationDate  = ISNULL(Core.dbo.fDateFormat(@GlobalDateFormat,ModificationDate),Core.dbo.fDateFormat(@GlobalDateFormat,GETDATE()))
        ,   TemplateId        = ISNULL(CAST(TemplateId AS varchar(16)),'')
        ,   IsRoot            = ISNULL(IsRoot,0)
        ,   IsActive          = ISNULL(IsActive,0)
        ,   SortOrdinal       = ISNULL(CAST(SortOrdinal AS varchar(16)),'')
        ,   ClientId          = ISNULL(ClientId,'')
        ,   Tag               = CAST(Core.dbo.fCharFormat('xmlCDATA',Tag,DEFAULT,'') AS xml)
        FROM
            Document
        WHERE
            DocumentId = 9073
        FOR XML AUTO, ELEMENTS
)

SELECT @xml

以下是类似于黄鼠狼的CDATA处理功能的相关细节:

IF @cmdName = 'xmlCDATA'
BEGIN
    IF @chars IS NULL
    BEGIN
        SET @charsOut = @charsDefault
    END
    ELSE
    BEGIN
        SET @chars = REPLACE(@chars,'<![CDATA[','')
        SET @chars = REPLACE(@chars,']]>','')
        SET @charsOut = '<![CDATA[' + @chars + ']]>'
    END
END