修改 HTML 保存在 DB table 中的内容

Modify HTML content saved in a DB table

我在数据库中有一个 table,其中包含一个包含 HTML 格式文本的通用文本字段。我需要解析这样一个字段的内容,找到所有的"img"标签并进行2次操作(只针对"img"标签):

1) 删除 "style" 属性及其所有值。
2) 插入一个class="img-responsive"属性。

待解析的HTML内容的一个特点是它没有完整的层次结构。例如,要解析的字符串可以是:

<div>
<p>This is some text</p>
<img src="http://www.mywebsite.com/myImage.jpg" alt = "" style="width:600px; height: 400px;"/>
</div>

我尝试了不同的方法来找到 "img" 标签,但都没有成功。例如:

String strHTML = "The sample HTML code above";
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(strHTML);
foreach (var img in doc.DocumentNode.Descendants("img"))
{
    // Remove "style" attribute for "img" tag.
    // Add class="img-responsive" for "img" tag.
}

上面代码的问题是没有根节点但是不知道如何"override"这样的节点直接解析字符串

我不会用 C# 编写代码,但我相信这可以使用正则表达式成功完成并替换为新的编辑值。

这是我发现的使用敏捷包的方法HTML。

using System;
using HtmlAgilityPack;

public class Program
{
    public static void Main()
    {
        var html = @"<div>
                         <p>This is some text</p>
                         <img src=""http://www.mywebsite.com/myImage1.jpg"" alt = """" style=""width:600px; height: 400px;""/>
                         <img src=""http://www.mywebsite.com/myImage2.jpg"" alt = """" style=""width:600px; height: 400px;""/>
                         <img src=""http://www.mywebsite.com/myImage3.jpg"" alt = """" style=""width:600px; height: 400px;""/>
                    </div>";

        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(html);

        var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//img");

        foreach (var node in htmlNodes){

            // Adding class "img-responsive"
            node.AddClass("img-responsive");

            // Removing style attribute
            node.Attributes["style"].Remove();

            Console.WriteLine(node.OuterHtml);
        }

        // Adding the close </img> to each image of the HTML
        HtmlNode.ElementsFlags["img"] = HtmlElementFlag.Closed;

        // Here you can see the changes in the HTML string
        Console.WriteLine(htmlDoc.DocumentNode.OuterHtml);
    }
}

您可以在此处参考 Agility Pack HTML 文档:https://html-agility-pack.net/documentation

这是link在dotnetfiddle中看到的解决方案运行:https://dotnetfiddle.net/uyhAKE

我希望这对你有用。