我有字符串
<div class="TextP">
<span class="bold" style="font-weight: bold;">bold</span> text
<span class="bold" style="font-weight: bold;">italic</span> text
<span class="bold" style="font-weight: bold;">underlined</span> text
</div>
我将其解析为XElement
对象,然后我需要用其他元素替换格式化范围。所以我写了这段代码
//el is the root div
foreach (XElement el in e.Elements())
{
switch (el.Name.ToString().ToLower())
{
//The method is more complex, but only this part doesnt work, therfore this only case
case "span":
if (el.Attribute("class") != null)
{
switch (el.Attribute("class").Value)
{
case "underline" :
el.ReplaceWith(XElement.Parse("<U>" + el.Value + "</U>"));
break;
case "bold":
el.ReplaceWith(XElement.Parse("<B>" + el.Value + "</B>"));
break;
case "italic":
el.ReplaceWith(XElement.Parse("<I>" + el.Value + "</I>"));
break;
}
}
break;
}
}
问题是当我替换第一个span
foreach 循环时,其他两个循环spans
仍然没有被替换。我认为这是因为.Elements()
集合发生了变化,但我想不通,我应该如何更改我的代码。