如何更新 HTML 样式属性

我有 ac# .net core 2.2 应用程序,我正在尝试解析 HTML 页面并编辑一些样式属性。


我正在使用 HTML Agility Pack


在我的 HTML 中,我有一个具有多种样式的 Id。


<td id="bannerTop" class="alert alert-warning" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 16px; vertical-align: top; color: #fff; font-weight: 500; text-align: center; border-radius: 3px 3px 0 0; background-color: #FF9F00; margin: 0; padding: 20px;" align="center" bgcolor="#FF9F00" valign="top">

我想将此元素称为“bannerTop”并编辑样式背景颜色


var htmlDoc = new HtmlDocument();

htmlDoc.LoadHtml(selectedTemplate.HtmlTemplateString);


var bannerTop = htmlDoc.GetElementbyId("bannerTop");

bannerTop.Attributes["style"].Value = "background-color: #0000FF";

但这会覆盖所有样式属性,我怎么能只编辑其中一个呢?我是否需要对bannerTop.Attributes["style"]返回的字符串进行手动解析,或者是否有 HTML Agility Pack 允许编辑单个样式的更简单方法?


慕的地8271018
浏览 164回答 1
1回答

蝴蝶刀刀

您需要从属性中获取样式,然后遍历它们以手动更改样式的特定项。我会分裂“;” 然后“:”获取名称/值对。遍历它们,将名称小写,如果匹配则更改值。bgcolor否则,将原始值附加到newStyles。var bannerTop = htmlDoc.GetElementbyId("bannerTop");string oldStyle = bannerTop.Attributes["style"].Value;string newStyles = "";foreach (var entries in oldStyle.Split(';')){&nbsp; &nbsp; var values = entries.Split(':');&nbsp; &nbsp; if (values[0].ToLower() == "bgcolor")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; values[1] = "#0000FF";&nbsp; &nbsp; &nbsp; &nbsp; newStyles += String.Join(':', values) + ";";&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; newStyles += entries + ";";&nbsp; &nbsp; }}bannerTop.Attributes["style"].Value = newStyles;
打开App,查看更多内容
随时随地看视频慕课网APP