在使用sql查询xml时如何保留HTML标记?

Bar*_*man 6 html xml sql sql-server-2005 sql-server-2008

当我编写查询以生成xml标记时,我想在我的sql查询中保留html标记.例如:

select '<p> this is a code</p>' as code
from table name
for xml path (''), type
Run Code Online (Sandbox Code Playgroud)

输出:

<code>&ltp&gt; this is a code &lt/p&gt; <code>
Run Code Online (Sandbox Code Playgroud)

它应该输出什么:

<code><p> this is a code </p><code>
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?谢谢!

dan*_*adu 5

如果使用xhtml,我相信转换为Xml会做:

select convert(xml, '<p> this is a code</p>') as code
from table name
for xml path (''), type
Run Code Online (Sandbox Code Playgroud)

编辑:如果列是ntext,则支持隐式转换为Xml

create table #t(html ntext)
insert into #t values(N'<p> this is a code</p>')
select convert(xml, html) as code
from #t
for xml path (''), type
drop table #t
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,您需要在转换之前清理 html。您可以使用“REPLACE”将特殊字符替换为字符实体。例如,对于 `&amp;`,您需要 `&amp;`,对于 `&lt;` - `&lt;`,对于 `&gt;` - `&gt;` 等。但是,`REPLACE` 不适用于 `ntext`,因此您需要'需要转换为 `nvarchar`: `replace(convert(nvarchar(max), html), '&amp;', '&amp;'))` (2认同)