Replacing elements in XElement breaks foreach loop 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.

Generally you can't make changes to a collection as you're iterating through it. One way to get around this is to make a copy of your collection and iterate through that:
foreach (XElement el in e.Elements().ToArray()) // or ToList
{
    // ...
}

This will find all the child elements of e at the beginning of the loop and store them in a different collection (using the Linq ToArray / ToList method). This way, the elements collection can be freely modified inside the loop.