Better way to add a style attribute to Html using HtmlAgilityPack

c#, html, html-agility-pack

Solution

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.

Problem

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); } } ```

Original source