Search code examples
c#xelement

XElement modification, how do I edit the attributes?


I have an xelement which is basic html, i want to quickly loop through all the elements that are paragraph tags and set the style attribute or append to it. I am doing what is below, but it is not changing the master xelement. How can i make this work?

    XElement ele = XElement.Parse(body);
    foreach (XElement pot in ele.DescendantsAndSelf("p"))
    {
        if (pot.Attribute("style") != null)
        {
            pot.SetAttributeValue("style", pot.Attribute("style").Value + " margin: 0px;");
        }
        else
        {
            pot.SetAttributeValue("style", "margin: 0px;");
        }
    }

Solution

  • Just use the Value property - you can retrieve as well as set the attribute value with it. Only adding an attribute is a little more work - you use the Add() method and pass an instance of XAttribute:

    if (pot.Attribute("style") != null)
    {
        pot.Attribute("style").Value = pot.Attribute("style").Value + " margin: 0px;";
    }
    else 
    {
        pot.Add(new XAttribute("style", "margin: 0px;"));
    }
    

    It looks though like you are actually editing HTML (I might be mistaken though) - in that case be aware that most HTML that works just fine in a browser is not valid XML - you should use a parser for HTML in that case, e.g. HtmlAgilityPack which will do a much better job at this.