XElement修改,如何编辑属性

本文关键字:编辑 属性 何编辑 修改 XElement | 更新日期: 2023-09-27 18:23:47

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

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

XElement修改,如何编辑属性

只需使用Value属性-您可以用它检索和设置属性值。只添加属性需要更多的工作-您使用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的解析器,例如HtmlAgilityPack,它在这方面会做得更好。