我有一个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;");
}
}
Run Code Online (Sandbox Code Playgroud)
只需使用该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;"));
}
Run Code Online (Sandbox Code Playgroud)
虽然看起来你实际上正在编辑HTML(虽然我可能会弄错) - 在这种情况下要注意大多数在浏览器中运行良好的HTML 都不是有效的XML - 在这种情况下你应该使用HTML解析器,例如HtmlAgilityPack这将在这方面做得更好.