2012-02-09 67 views
0

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

回答

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这将在这方面做得更好。