gpt4 book ai didi

c# - 使用 HtmlAgilityPack 将样式属性添加到 Html 的更好方法

转载 作者:太空狗 更新时间:2023-10-30 00:33:24 25 4
gpt4 key购买 nike

我正在使用 HtmlAgilityPack。我正在搜索所有 P 标签,并在 P 标签内的样式中添加“margin-top: 0px”。

如您所见,它有点“暴力破解” margin-top 属性。似乎必须有更好的方法来使用HtmlAgilityPack 但我找不到它,并且 HtmlAgilityPack 文档不存在。

有人知道更好的方法吗?

HtmlNodeCollection pTagNodes = node.SelectNodes("//p[not(contains(@style,'margin-top'))]");

if (pTagNodes != null && pTagNodes.Any())
{
foreach (HtmlNode pTagNode in pTagNodes)
{
if (pTagNode.Attributes.Contains("style"))
{
string styles = pTagNode.Attributes["style"].Value;
pTagNode.SetAttributeValue("style", styles + "; margin-top: 0px");
}
else
{
pTagNode.Attributes.Add("style", "margin-top: 0px");
}
}
}


更新:我已经根据 Alex 的建议修改了代码。仍然想知道是否有一些内置的HtmlAgilityPack 中的功能将以更“DOM”的方式处理样式属性。

const string margin = "; margin-top: 0px";

HtmlNodeCollection pTagNodes = node.SelectNodes("//p[not(contains(@style,'margin-top'))]");

if (pTagNodes != null && pTagNodes.Any())
{
foreach (var pTagNode in pTagNodes)
{
string styles = pTagNode.GetAttributeValue("style", "");
pTagNode.SetAttributeValue("style", styles + margin);
}
}

最佳答案

您可以通过使用 HtmlNode.GetAttributeValue 方法稍微简化您的代码,并将您的“margin-top” 魔术字符串设为常量:

const string margin = "margin-top: 0";
foreach (var pTagNode in pTagNodes)
{
var styles = pTagNode.GetAttributeValue("style", null);
var separator = (styles == null ? null : "; ");
pTagNode.SetAttributeValue("style", styles + separator + margin);
}

不是非常显着的改进,但这段代码对我来说更简单。

关于c# - 使用 HtmlAgilityPack 将样式属性添加到 Html 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12062495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com