c# - 如何从 HTML 中拆分标签
问题描述
我有非常简单的 HTML 文本。在这里,我希望仅将图像附加到其他地方。如何使用 c# 单独剪切图像标签。
<p>this is new document<img alt="" height="150" src="https://kuba2storage.blob.core.windows.net/kuba-appid-1/manual-1203/images/desert-20180824203530071.jpg" width="200"/>This is new document</p>
我想从这个数据中单独获取 img 标签。例如
<img alt="" height="150" src="https://kuba2storage.blob.core.windows.net/kuba-appid-1/manual-1203/images/desert-20180824203530071.jpg" width="200"/>
代码:
var parts = Regex.Split(text.Text, @"(<img>[\s\S]+?<\/img>)").Where(l => l != string.Empty).ToArray();
解决方案
您可以尝试在下面使用
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string data = "<p>this is new document<img alt='' height='150' src='https://kuba2storage.blob.core.windows.net/kuba-appid-1/manual-1203/images/desert-20180824203530071.jpg' width='200'/>This is new document</p>";
var newdt = FetchImgsFromSource(data);
}
}
public static List<string> FetchImgsFromSource(string htmlSource)
{
List<string> listOfImgdata = new List<string>();
string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
var matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in matchesImgSrc)
{
string href = m.Groups[1].Value;
listOfImgdata.Add(href);
}
return listOfImgdata;
}
}
推荐阅读
- email - 在 Kentico 中,有没有办法将电子邮件提要(在电子邮件营销中)从时事通讯转换为电子邮件营销活动?
- c++ - 使用 Spdlog c++ 库无法解析的外部符号“__declspec(dllimport)
- r - Xgboost tweedie:为什么从链接 = exp(link)/ 2 获得预测的公式是?
- javascript - js中的所有变量在执行之前都转换成对象了吗?
- java - VS Code 将我指向早期的 JDK 版本
- java - 两种不同的 Firebase 方法同时在两个不同的片段 int 中工作
- c++ - 通过两个嵌套函数传递 C++ 函数的名称
- java - 新应用中的 Active Directory 实施
- random - 随机函数中 UNPREDICTABLE 的含义是什么?
- python - 在 AWS 中监控 python shell 粘合作业