我有这个问题:
SELECT [content_id]
,[content_html]
,[date_created]
,folder_id
FROM content ct
where folder_id=126
order by content_title
FOR XML PATH('PressRelease'), ROOT ('PressReleases')
当我运行这个查询时,这是生成的 XML 文件:
<PressReleases>
<PressRelease>
<content_id>6442452927</content_id>
<content_html><root><Date>2015-12-02</Date>
<Description><p class="customHeader">jobs to Philadelphia.</p>
<p>mtext in here.</p>
<p>mtext in here.</p>
</Description>
<SEO><h1>Pennsylvania Location</h1>
<div class="bulletRightBar"> The move was made possible in part by the Philadelphia Jobs
Credit</div>
</SEO>
</root></content_html>
<date_created>2015-12-02T09:47:12</date_created>
<folder_id>126</folder_id>
</PressRelease>
<PressReleases>
我需要的是这个 XML 文件:
<PressReleases>
<PressRelease>
<content_id>6442452927</content_id>
<content_html><root><Date>2015-12-02</Date>
<Description><p class="customHeader">jobs to Philadelphia.</p>
<p>mtext in here.</p>
<p>mtext in here.</p>
</Description>
<SEO><h1>Pennsylvania Location</h1>
<div class="bulletRightBar"> The move was made possible in part by the Philadelphia Jobs
Credit</div>
</SEO>
</root></content_html>
<date_created>2015-12-02T09:47:12</date_created>
<folder_id>126</folder_id>
</PressRelease>
<PressReleases>
在<content_html>
里面我想制作 <root>
<date>
和 <Description>
作为 XML 元素,但将其余部分保留为编码的 html。
最佳答案
它并不漂亮,但您可以将 XML 字段转换为字符串,使用 REPLACE 函数并将其转换回 XML,如下所示。您可能想创建一个函数来执行此操作,因为该行会进行大量替换:
SELECT [content_id]
,cast(REPLACE(cast([content_html] as varchar(max)),'<root>','<root>') as xml)
,[date_created]
,folder_id
FROM content ct
where folder_id=126
order by content_title
FOR XML PATH('PressRelease'), ROOT ('PressReleases')
或者这里有一种用函数调用它的方法
CREATE FUNCTION [dbo].[XML_Replace]
(@XML_Field XML)
RETURNS XML
BEGIN
DECLARE @xml varchar(max)
DECLARE @xml_Mid varchar(max)
DECLARE @strtBigInt bigint
, @endBigInt bigint
SET @xml = cast(@XML_Field as varchar(max))
SET @strtBigInt = CHARINDEX('<Description>',@xml)
SET @endBigInt = CHARINDEX('</SEO>',@xml)
SET @xml_Mid = SUBSTRING(@xml, @strtBigInt+19,@endBigInt-@strtBigInt-19);
RETURN(cast(REPLACE(REPLACE(REPLACE(REPLACE(substring(@xml,0,@strtBigInt+19),'<','<'),'>','>') + @xml_Mid + REPLACE(REPLACE(substring(@xml,@endBigInt,Len(@xml)),'<','<'),'>','>'),'</Description>','</Description>'),'<SEO>','<SEO>') as xml));
END
然后在您的代码中使用该函数:
SELECT [content_id]
,dbo.XML_Replace([content_html]) as content_html
,[date_created]
,folder_id
FROM content ct
where folder_id=126
order by content_title
FOR XML PATH('PressRelease'), ROOT ('PressReleases')
关于sql - 用 XML 输出替换 sql 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35558800/