Scott
Scott

Reputation: 1

How to remove an element where all descendants are empty

I would like to remove all the rows from the root where all the columns are empty.

<root>
  <row>
    <column></column>
    <column></column>
  </row>
  <row>
    <column></column>
    <column>data</column>
  </row>
<root>

I have tried xDocument.Descendants("row").Elements("column").Where(e => e.IsEmpty || String.IsNullOrWhiteSpace(e.Value)).Remove();

but end up with

<root>
  <column>data</column>
<root>

where my desired results are;

<root>
  <column></column>
  <column>data</column>
</root>

Upvotes: 0

Views: 80

Answers (1)

IDeveloper
IDeveloper

Reputation: 1299

Here's what you need:

xDocument.Descendants("row").Where(r => r.Elements().All(e => e.IsEmpty || String.IsNullOrEmpty(e.Value))).Remove()

Upvotes: 1

Related Questions