首页 > 解决方案 > 如何从 c# 中的 img html 标签获取图像源属性值?

问题描述

我的字符串变量存储一组 HTML 标签以及 img 源文件链接。

string str = "<div> <img src="https://i.testimg.com/images/g/test/s-l400.jpg" style="width: 100%;"> <div>Test</div> </div>"

如何从字符串str中获取src属性值。显然,我必须将 src 的值分配给另一个变量。

如何从 c# 中的 img html 标签获取 src 属性值?

标签: c#html

解决方案


以下代码将提取src属性的值。

string str = "<div> <img src=\"https://i.testimg.com/images/g/test/s-l400.jpg\" style=\"width: 100%;\"> <div>Test</div> </div>";

// Get the index of where the value of src starts.
int start = str.IndexOf("<img src=\"") + 10;

// Get the substring that starts at start, and goes up to first \".
string src = str.Substring(start, str.IndexOf("\"", start) - start);

推荐阅读