Based on previous answers here at StackOverflow, I am using the following statement to remove all empty elements (except those having attributes):
XDocument xdoc = XDocument.Parse(xmlString);
xdoc.Descendants()
.Where(e => !e.HasAttributes && (e.IsEmpty || String.IsNullOrWhiteSpace(e.Value)))
.Remove();
When run against the following XML:
<MESSAGE>
<RELATIONSHIPS1>
<RELATIONSHIP1 from="10017" to="1"/>
</RELATIONSHIPS1>
<RELATIONSHIPS2>
<RELATIONSHIP2 from="10017" to="1"></RELATIONSHIP2>
</RELATIONSHIPS2>
<RELATIONSHIPS3>
<RELATIONSHIP3 from="10017" to="1">test</RELATIONSHIP3>
</RELATIONSHIPS3>
<RELATIONSHIPS4 attr="test">
<RELATIONSHIP4 from="10017" to="1"></RELATIONSHIP4>
</RELATIONSHIPS4>
<EXTENSION a1="1" a2="2"/>
<FLOOD>
<FLOOD_RESPONSE>
<PROPERTY>
<PROPERTY_DETAIL/>
<PROPERTY_DETAIL></PROPERTY_DETAIL>
</PROPERTY>
</FLOOD_RESPONSE>
</FLOOD>
</MESSAGE>
I was expecting the following:
<MESSAGE>
<RELATIONSHIPS1>
<RELATIONSHIP1 from="10017" to="1"/>
</RELATIONSHIPS1>
<RELATIONSHIPS2>
<RELATIONSHIP2 from="10017" to="1"></RELATIONSHIP2>
</RELATIONSHIPS2>
<RELATIONSHIPS3>
<RELATIONSHIP3 from="10017" to="1">test</RELATIONSHIP3>
</RELATIONSHIPS3>
<RELATIONSHIPS4 attr="test">
<RELATIONSHIP4 from="10017" to="1"></RELATIONSHIP4>
</RELATIONSHIPS4>
<EXTENSION a1="1" a2="2" />
</MESSAGE>
But received the following:
<MESSAGE>
<RELATIONSHIPS3>
<RELATIONSHIP3 from="10017" to="1">test</RELATIONSHIP3>
</RELATIONSHIPS3>
<RELATIONSHIPS4 attr="test">
<RELATIONSHIP4 from="10017" to="1"></RELATIONSHIP4>
</RELATIONSHIPS4>
<EXTENSION a1="1" a2="2" />
</MESSAGE>
Any ideas on the nested empty elements with attributes are being removed?