从 XDocument 错误中删除 XElement

Har*_*lor 1 c# xml asp.net linq-to-xml

我有一个XDocument,我想从中删除XElement

我试试这个代码:-

XDocument XDoc = XDocument.Parse(XMLFile);

    var PricedItineraryRemove = XDoc.Descendants("PricedItinerary");

    foreach (XElement xle in PricedItineraryRemove)
    {
         if (xle.Attribute("SequenceNumber").Value != SequenceNumber.ToString())
         {
               xEle.Remove(); //this line giving error second time.
         }
    }
Run Code Online (Sandbox Code Playgroud)

xEle.Remove()第一次正常工作,但第二次给出System.InvalidOperationException异常。

Ily*_*nov 5

尝试使用此代码删除具有特定属性的节点:

string sequenceNumberStr = SequenceNumber.ToString();

XDoc.Descendants("PricedItinerary")
    .Where(node => (string)node.Attribute("SequenceNumber") != sequenceNumberStr)
    .Remove();
Run Code Online (Sandbox Code Playgroud)