首页 > 解决方案 > SQL:读取查询返回的 span HTML 元素内的文本

问题描述

我有一个返回以下 HTML 元素的查询:

<span CreatedFromTXTextControl="1" style="font-family:Tahoma;font-size:8pt;">
<p lang="en-US" style="text-indent:0pt;margin-left:0pt;margin-top:0pt;margin-bottom:6pt;margin-right:0pt;line-height:100%;" xmlns="http://www.w3.org/1999/xhtml"><span style="font-family:'Tahoma';font-size:8pt;">I am not sure how to extract this text using SQL.</span></p>
</span>

我的查询目前看起来像这样:

SELECT text
FROM MyTable

我该如何更改此查询以仅返回span上面显示的元素内的文本?

在上面的示例中,结果应该是字符串: I am not sure how to extract this text using SQL.

DBMS 实施:MS SQL Server。

标签: htmlcsssqlsql-server

解决方案


试试这个:

DECLARE @Data table ( html varchar(4000) );
INSERT INTO @Data VALUES ( 
    '<span CreatedFromTXTextControl="1" style="font-family:Tahoma;font-size:8pt;">
      <p lang="en-US" style="text-indent:0pt;margin-left:0pt;margin-top:0pt;margin-bottom:6pt;margin-right:0pt;line-height:100%;" xmlns="http://www.w3.org/1999/xhtml">
        <span style="font-family:Tahoma;font-size:8pt;">I am not sure how to extract this text using SQL.</span>
      </p>
     </span>'
);

SELECT
    t.f.value( '.', 'varchar(255)' ) AS span_value
FROM @Data AS d
CROSS APPLY (
    SELECT CAST ( d.html AS xml ) AS h
) AS x
CROSS APPLY x.h.nodes( '//span/*' ) t(f);

退货

+---------------------------------------------------+
|                   span_value                      |
+---------------------------------------------------+
| I am not sure how to extract this text using SQL. |
+---------------------------------------------------+

使用 SQL Server 的 XML 数据类型可以得到你需要的东西——假设你的 HTML 是有效的。


推荐阅读