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.
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 the HtmlAgilityPack 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");
}
}
}
UPDATE: I have modified the code based on Alex's suggestions. Would still like to know if there is a some built-in functionality 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);
}
}