I have string
<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>
which I parse to XElement
object and than I need to replace the formating spans with other elements. So I have written this code
//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;
}
}
The problem is that when I replace the first span
the foreach loop breaks and the two other spans
remain unreplaced.
I think It's because the .Elements()
collection changes, but I can't figure out, how should I change my code.