0

I am looking for a good approach to write a LINQ query that can preserve empty tags in XML.

Input XElement:

<LayoutDefinition >
  <ScreenDefinitions>
    <ScreenDefinition Monitor="1">
      <SSBS>
        <SSB Id="1" />
        <SSB Id="2" />
      </SSBS>
    </ScreenDefinition>
    <ScreenDefinition Monitor="2">
      <SSBS>
        <SSB Id="1" />
        <SSB Id="2" />
      </SSBS>
    </ScreenDefinition>
  </ScreenDefinitions>
  <CustomProperties>
    <Property Name="SynchronizationCollection" />
  </CustomProperties>
</LayoutDefinition>

This is being process by the below method:

        private static IList<XElement> ProcessLayoutDefinition(XElement layoutDefinition)
        {
            IList<XElement> resultLayoutDefinitions = new List<XElement>();
layoutDefinition?.XPathSelectElement($"/CustomProperties/Property[@Name=\"SynchronizationCollection\"]").Remove();

            resultLayoutDefinitions.Add(layoutDefinition);

            return resultLayoutDefinitions;
        }

The Result should yield the below output:

<LayoutDefinition >
  <ScreenDefinitions>
    <ScreenDefinition Monitor="1">
      <SSBS>
        <SSB Id="1" />
        <SSB Id="2" />
      </SSBS>
    </ScreenDefinition>
    <ScreenDefinition Monitor="2">
      <SSBS>
        <SSB Id="1" />
        <SSB Id="2" />
      </SSBS>
    </ScreenDefinition>
  </ScreenDefinitions>
  <CustomProperties>
  </CustomProperties>
</LayoutDefinition>

But gives the below output with only <CustomProperties />

<LayoutDefinition >
  <ScreenDefinitions>
    <ScreenDefinition Monitor="1">
      <SSBS>
        <SSB Id="1" />
        <SSB Id="2" />
      </SSBS>
    </ScreenDefinition>
    <ScreenDefinition Monitor="2">
      <SSBS>
        <SSB Id="1" />
        <SSB Id="2" />
      </SSBS>
    </ScreenDefinition>
  </ScreenDefinitions>
<CustomProperties />
</LayoutDefinition>

Is there anyway I can force to preserve the <CustomProperties> </CustomProperties> tags although <CustomProperties /> is a correct tag.

  • Not an appropriate duplicate. `XmlDocument` is not `XElement`. – Jeroen Mostert Mar 16 '22 at 19:32
  • 2
    @JeroenMostert - Is this better then? [Forcing XDocument.ToString() to include the closing tag when there is no data](https://stackoverflow.com/q/2459138). – dbc Mar 16 '22 at 20:08

0 Answers0