Search code examples
c#.netlinqxmlreaderxelement

How to get the value in an xml section, and if not present set the value as null?


I have an xml file like this:

<?xml version="1.0" encoding="utf-8"?>
<EffectFile>
  <Effects>
    <Effect>
      <Type>Blur</Type>
    </Effect>
    <Effect>
      <Type>Sharpen</Type>
    </Effect>
    <Effect>
      <Type>Zoom</Type>
      <Options>
        <Option>88</Option>
        <Option>"miles"</Option>
      </Options>
    </Effect>
  </Effects>
</EffectFile>

which I am parsing it like this:

xElement.Elements ( "Effects" ).Elements ( "Effect" ).Select (
    e => new Effect (
        ( EffectType ) Enum.Parse ( typeof ( EffectType ), ( string ) e.Elements ( "Type" ).FirstOrDefault ( ) ),
        e.Elements ( "Options" ).Select ( p => ( object ) p.Elements ( "Option" ) ) ) );

But with this version every Effect gets at least an empty EffectOptions value. Is there a way to specify if there is no Options section for an Effect, the value should be collected as null?

The Effect type has a constructor like this:

new Effect (EffectType type, EffectOptions options)

so just want to pass null to the second parameter if there are no Options section.


Solution

  • Just use Any() :

    e.Elements("Options").Any() 
               ? e.Elements("Options").Select (p => (object) p.Elements("Option")) 
               : null )