C# 操作html下的css样式

需求:需要给table添加样式,默认的table没有边框

AngleSharp

https://anglesharp.github.io/

给表格添加边框

没有添加样式的时候

html 复制代码
<table>
    <colgroup>
        <col style="width: 54.17%;">
        <col style="width: 45.83%;">
    </colgroup>
    <tbody>
        <tr>
            <td rowspan="2" style="height: 13.5pt; width: 175.5pt;">111</td>
            <td style="width: 148.5pt;">222</td>
        </tr>
        <tr>
            <td>444</td>
        </tr>
    </tbody>
</table>

添加样式border-collapse: collapse; border: 1px solid rgb(102, 102, 102);实现边框

代码如下

cs 复制代码
using AngleSharp;
using AngleSharp.Css.Dom;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using System;
using System.Linq;

namespace MailStu10
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var html = @"<table>
    <colgroup>
        <col style=""width: 54.17%;"">
        <col style=""width: 45.83%;"">
    </colgroup>
    <tbody>
        <tr>
            <td rowspan=""2"" style=""height: 13.5pt; width: 175.5pt;"">111</td>
            <td style=""width: 148.5pt;"">222</td>
        </tr>
        <tr>
            <td>444</td>
        </tr>
    </tbody>
</table>";
            Console.WriteLine(html);
            var config = Configuration.Default.WithDefaultLoader().WithCss();
            IBrowsingContext context = BrowsingContext.New(config);
            var parser = new HtmlParser(new HtmlParserOptions(),context);
            var htmlDocument = parser.ParseDocument(html);
            var tables = htmlDocument.QuerySelectorAll("table");
            if (tables != null && tables.Any())
            {
                foreach (var table in tables)
                {
                    var tableStyle = table.GetStyle();
                    if (tableStyle != null)
                    {
                        tableStyle.SetBorderCollapse("collapse");
                        tableStyle.SetBorderWidth("1px");
                        tableStyle.SetBorderColor("#000");
                        tableStyle.SetBorderStyle("solid");
                    }
                    else
                    {
                        //如果style不存在则直接将css样式植入
                        table.SetStyle("border-collapse: collapse; border: 1px solid #000;");
                    }
                    var tdList = table.QuerySelectorAll("td");
                    foreach (var td in tdList)
                    {
                        var tdStyle = td.GetStyle();
                        if (tdStyle != null)
                        {
                            tdStyle.SetBorderCollapse("collapse");
                            tdStyle.SetBorderWidth("1px");
                            tdStyle.SetBorderColor("#000");
                            tdStyle.SetBorderStyle("solid");
                        }
                        else
                        {
                            //如果style不存在则直接将css样式植入
                            td.SetStyle("border-collapse: collapse; border: 1px solid #000;");
                        }
                    }
                }
            }

            if (htmlDocument.Body != null)
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("结果");
                Console.WriteLine(htmlDocument.Body.InnerHtml);
            }
            
            Console.ReadKey();
        }
    }
}


去除图片的宽度限制

安装包版本

xml 复制代码
  <ItemGroup>
    <PackageReference Include="AngleSharp" Version="1.3.0-beta.470" />
    <PackageReference Include="AngleSharp.Css" Version="1.0.0-beta.151" />
  </ItemGroup>

代码

cs 复制代码
using AngleSharp.Css.Parser;
using AngleSharp;
using AngleSharp.Html.Parser;
using AngleSharp.Css.Dom;

namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var htmlData = """
                <p><img class="image_resized" style="width:790px;" src="https://files.nsts.mvccms.cn/Upload/20210515/20210515152916_8509.jpg" alt=""><img class="image_resized" style="width:790px;" src="https://files.nsts.mvccms.cn/Upload/20210515/20210515153029_9192.jpg" alt=""><img class="image_resized" style="width:790px;" src="https://files.nsts.mvccms.cn/Upload/20210515/20210515153053_6518.jpg" alt=""><img class="image_resized" style="width:790px;" src="https://files.nsts.mvccms.cn/Upload/20210515/20210515153115_9184.jpg" alt=""><img class="image_resized" style="width:790px;" src="https://files.nsts.mvccms.cn/Upload/20210515/20210515153141_3887.jpg" alt=""><img class="image_resized" style="width:790px;" src="https://files.nsts.mvccms.cn/Upload/20210515/20210515153210_9167.jpg" alt=""></p>
                """;
            Console.WriteLine(htmlData);
            // 创建 HTML 解析器
            var config = Configuration.Default.WithDefaultLoader().WithCss();
            IBrowsingContext context = BrowsingContext.New(config);
            var htmlParser = new HtmlParser(new HtmlParserOptions(), context);
            var document = htmlParser.ParseDocument(htmlData);
            // 查找所有 img 元素
            var imgElements = document.QuerySelectorAll("img");
            // 创建 CSS 解析器
            var cssParser = new CssParser();

            foreach (var img in imgElements)
            {
                var imgStyle = img.GetStyle();
                imgStyle.RemoveProperty("width");
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("结果");
            Console.WriteLine(document.ToHtml());
            if (document.Body != null)
            {
                Console.WriteLine();
                Console.WriteLine(document.Body.ToHtml());
                Console.WriteLine();
                Console.WriteLine(document.Body.InnerHtml);
            }
        }
    }
}

参考

https://github.com/AngleSharp/AngleSharp
https://anglesharp.github.io/docs/01-articles

相关推荐
quan263110 分钟前
日常开发20251022,传统HTML表格实现图片+视频+预览
前端·javascript·html·html列表实现图片+视频
攻城狮CSU3 小时前
类型转换汇总 之C#
java·算法·c#
华仔啊4 小时前
Vue3+CSS实现一个非常丝滑的 input 标签上浮动画,设计师看了都点赞
前端·css·vue.js
CodeCraft Studio5 小时前
国产化Word处理控件Spire.Doc教程:用Java实现TXT文本与Word互转的完整教程
java·c#·word·spire.doc·word文档转换·txt转word·word转txt
Aevget6 小时前
DevExpress WinForms v25.1亮点 - 电子表格组件、富文档编辑器全新升级
c#·编辑器·界面控件·devexpress·ui开发·winforms
一个专注写bug的小白猿6 小时前
.net实现ftp传输文件保姆教程
后端·c#·.net
昔人'6 小时前
html`contenteditable`
前端·html
shandianchengzi8 小时前
【记录】Unity|Unity从安装到打开一个Github项目(以我的世界(仿)为例)
unity·c#·游戏引擎·github·我的世界·mc
Sherry0078 小时前
【译】 CSS 布局算法揭秘:一次思维转变,让 CSS 从玄学到科学
前端·css
静待雨落9 小时前
为什么给<a>标签设置了download属性, 浏览器没有下载而是打开新标签!!
html