C# XElement修改,如何编辑属性?

C# XElement修改,如何编辑属性?,c#,xelement,C#,Xelement,我有一个xelement,它是基本html,我想快速循环所有作为段落标记的元素,并设置样式属性或附加到它。我正在做下面的事情,但它不会改变主元素。我怎样才能做到这一点 XElement ele = XElement.Parse(body); foreach (XElement pot in ele.DescendantsAndSelf("p")) { if (pot.Attribute("style") != null) {

我有一个xelement,它是基本html,我想快速循环所有作为段落标记的元素,并设置样式属性或附加到它。我正在做下面的事情,但它不会改变主元素。我怎样才能做到这一点

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

只需使用
属性-您可以使用它检索和设置属性值。只添加一个属性需要做更多的工作-使用
Add()
方法并传递
XAttribute
的实例:

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

看起来您实际上是在编辑HTML(但我可能弄错了)-在这种情况下,请注意大多数在浏览器中正常工作的HTML都是无效的XML-在这种情况下,您应该使用HTML解析器,例如,哪一个在这方面做得更好。

只需使用
属性-您可以使用它检索和设置属性值。只添加一个属性需要做更多的工作-使用
Add()
方法并传递
XAttribute
的实例:

if (pot.Attribute("style") != null)
{
    pot.Attribute("style").Value = pot.Attribute("style").Value + " margin: 0px;";
}
else 
{
    pot.Add(new XAttribute("style", "margin: 0px;"));
}
看起来您实际上是在编辑HTML(但我可能弄错了)-在这种情况下,请注意,大多数在浏览器中正常工作的HTML都是无效的XML-在这种情况下,您应该使用HTML解析器,例如,在这方面做得更好