首页 > 解决方案 > 如何从 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();

标签: c#tags

解决方案


您可以尝试在下面使用

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;
    }
}

在此处输入图像描述


推荐阅读