3

我有字符串

<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;
            }
        }

问题是当我替换第一个spanforeach 循环时,其他两个循环spans仍然没有被替换。我认为这是因为.Elements()集合发生了变化,但我想不通,我应该如何更改我的代码。

4

1 回答 1

4

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.

于 2013-09-11T18:39:18.433 回答