Search code examples
c#xmllinq

How to remove a parent element if a child is not present


xml = @"<root>
  <SUB-ELEMENT>
    <SHORT-NAME>SCB1</SHORT-NAME>
    <B-C>
      <S-C>
        <C-P-R DEST="S-A">MC_Path</C-P-R>
      </S-C>
    </B-C>
    <PDUS />
    <S-P-R DEST="S-A">SA_Sub_Path</S-P-R>
  </SUB-ELEMENT>
  <SUB-ELEMENT>
    <SHORT-NAME>SCB2</SHORT-NAME>
    <B-C>
      <S-C>
        <C-P-R DEST="S-A">SA_Sub_Path</C-P-R>
        <PDUS>
          <S-C-I-I>
            <HEADER-ID>10772</HEADER-ID>
          </S-C-I-I>
          <S-C-I-I>
            <HEADER-ID>10773</HEADER-ID>
          </S-C-I-I>
        </PDUS>
      </S-C>
      <S-C>
        <C-P-R DEST="S-A">MC_Path</C-P-R>
      </S-C>
    </B-C>
    <PDUS>
      <S-C-I-I>
        <HEADER-ID>10774</HEADER-ID>
      </S-C-I-I>
    </PDUS>
    <S-P-R DEST="S-A">SA_Sub_Path</S-P-R>
  </SUB-ELEMENT>
  <SUB-ELEMENT>
    <SHORT-NAME>SCB3</SHORT-NAME>
    <B-C>
      <S-C>
        <C-P-R DEST="S-A">MC_Path</C-P-R>
      </S-C>
    </B-C>
    <PDUS />
    <S-P-R DEST="S-A">SA_Sub_Path</S-P-R>
  </SUB-ELEMENT>
 </root>"

I need to remove the "SUB-ELEMENT" if it does not have the child "S-C-I-I" element.

I tried the below code.

StringReader sr = new StringReader(xml);
XDocument d = XDocument.Load(sr);

d.Descendants("SUB-ELEMENT").Where(x => x.Element("S-C-I-I") == null).Remove();

d.save(filepath);

but it removes all the "SUB-Element". in the above case only the SCB2 should present in the end and other "SUB-Element" should be removed.

Thanks in advance.


Solution

  • In your sample, the S-C-I-I elements are descendants of the SUB-ELEMENTs, so try d.Descendants("SUB-ELEMENT").Where(x => !x.Descendants("S-C-I-I").Any()).Remove();