'How can i remove an whole XML Block just by knowing an element inside it

everyone i have a question on how to delete an block of elements from my xml file while knowing only the text value of one item inside it. There are hundreds of the the same blocks where the only difference is the ID values and the text that i know to delete the block.

public static void deleteBlock() {
        XElement xelement = XElement.Load(@"C:\Program Files (x86)\Tools\VisualStudioProjects\bausteine\modul.xml");
        foreach (XElement xEle in xelement.Descendants("SW.Blocks.CompileUnit"))
        {
            var complete = xEle;
            foreach(var item in xEle.Descendants("Text"))
            {
                if (item.Value=="The only thing i know to delete the Block")       
                {
                    complete.Remove();
                    break; // The Answer
                }

            }
           xelement.Save(@"C:\Program Files(x86)\Tools\VisualStudioProjects\Baustein_1.xml");
        }

I though i could look first for the element with the name SW.Blocks.CompileUnit then look inside it for the Text value and if it matches mine then it should delete the block and it should go through all blocks. It finds the block i want but deletes everything else and saves the block that i want to be deleted. Then it gives me Null Exception.

<SW.Blocks.CompileUnit ID="85" CompositionName="CompileUnits">
    <AttributeList> 
     <ObjectList>
      <MultilingualText ID="86" CompositionName="Comment">
        <ObjectList>
          <MultilingualTextItem ID="87" CompositionName="Items">
            <AttributeList>
              <Culture>de-DE</Culture>
              <Text />
            </AttributeList>
          </MultilingualTextItem>
        </ObjectList>
      </MultilingualText>
      <MultilingualText ID="88" CompositionName="Title">
        <ObjectList>
          <MultilingualTextItem ID="89" CompositionName="Items">
            <AttributeList>
              <Culture>de-DE</Culture>
              <Text>The Only thing i know to delete the Block</Text>
            </AttributeList>
          </MultilingualTextItem>
        </ObjectList>
      </MultilingualText>
    </ObjectList>
  </SW.Blocks.CompileUnit>

That is one of the blocks of the xml data. That is also the one that my codes leaves while deleting everything else. I hope i explained it a little better now. I dont know why its deleting everything else except the block and why is it giving me a null exception. Thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source