2012-02-09 64 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這將在這方面做得更好。