XElement修改,我该如何编辑属性?

时间:2012-02-09 02:00:44

标签: c# xelement

我有一个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;");
        }
    }

1 个答案:

答案 0 :(得分:5)

只需使用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这会在这方面做得更好。

相关问题