html - 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。
解决方案
试试这个:
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 是有效的。
推荐阅读
- php - Traylabs/oracle-storage PHP web API 集成解决方案
- c# - 如何将未知类型的对象传递给函数
- tensorflow - tensorflow 2.0 keras 将模型保存到 hdfs:不能减少 id 引用计数
- python - WxPython:在面板中嵌套面板
- react-native - React-native 应用程序一直在模拟器上停止
- r - 用于替换列表分隔符和字符串结尾的可变长度负向后查找
- c# - 如何在 .net core 2.2 webapi 中访问 GitLab CI CD 环境变量
- c# - 在由`InitializeOnLoad`执行时,如何确定它是在编辑器中运行还是在要发布的建筑物中运行?
- c++ - Consexpr 行列式(二维 std::array)
- webpack - 如何在没有节点模块的情况下使用 Webpack 构建 JQuery 和 Bootstrap?