【问题标题】:How do you keep HTML tags when querying a xml using sql?使用 sql 查询 xml 时如何保留 HTML 标签?
【发布时间】:2012-06-08 04:30:51
【问题描述】:

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

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

输出:

<code>&ltp&gt; this is a code &lt/p&gt; <code>

它应该输出什么:

<code><p> this is a code </p><code>

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

【问题讨论】:

标签: html sql xml sql-server-2008 sql-server-2005


【解决方案1】:

如果使用xhtml,我相信转换为Xml 就可以了:

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

编辑:如果列是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

【讨论】:

  • 这很好用,但是如果您要转换的变量是 ntext 怎么办。
  • ntextxml 的转换是隐式的(参见this)。我编辑了我的答案以提供一个例子。
  • 谢谢,我询问 ntext 的原因是因为我尝试转换的列是 ntext 并且我遇到了错误。事实证明该变量包含一个 &,这对 xml 不太友好。有没有办法解析&?
  • 很遗憾,转换前需要清理html。您可以使用 REPLACE 将特殊字符替换为字符实体。例如,对于&amp;amp;,您需要&amp;amp;,对于&amp;lt; - &amp;lt;,对于&amp;gt; - &amp;gt; 等。但是,REPLACE 不适用于ntext,因此您需要转换为nvarcharreplace(convert(nvarchar(max), html), '&amp;', '&amp;amp;'))
【解决方案2】:

下面的 sn-ps 对我有用

DECLARE @HTMLt  NVARCHAR(MAX)  ;

........

SET @HTMLt = REPLACE(REPLACE(REPLACE(@HTMLt,'&amp;','&' ) , '&lt;','<'),'&gt;','>');

【讨论】:

    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2021-11-09
    • 2018-09-06
    • 1970-01-01
    相关资源
    最近更新 更多