问题描述
我正在使用HtmlAgilityPack.我正在搜索所有P标签,并在P标签内的样式中添加了"margin-top:0px".
I am using the HtmlAgilityPack. I am searching through all P tags and adding a "margin-top: 0px" to the style within the P tag.
如您所见,它有点像强行强制" margin-top属性.似乎必须有一种更好的方法来使用HtmlAgilityPack,但我找不到它,并且不存在HtmlAgilityPack文档.
As you can see it is kinda "brute forcing" the margin-top attribute. It seems there has to be a better way to do this using theHtmlAgilityPack but I could not find it, and the HtmlAgilityPack documentation is non-existent.
有人知道更好的方法吗?
Anybody know a better way?
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");
}
}
}
更新:我已经根据亚历克斯的建议修改了代码.仍然想知道是否有一些内置的HtmlAgilityPack中的功能,可以更"DOM"的方式处理样式属性.
UPDATE: I have modified the code based on Alex's suggestions. Would still like to know if there is a some built-infunctionality in HtmlAgilityPack that will handle the style attributes in a more "DOM" manner.
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" 魔术字符串设置为常数:
You could simplify your code a little bit by using HtmlNode.GetAttributeValue
method, and making your "margin-top" magic string as constant:
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);
}
不是很明显的改进,但是对于我来说,这段代码更简单.
Not a very significant improvement, but this code is simpler as for me.
这篇关于使用HtmlAgilityPack向HTML添加样式属性的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!