开发者

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

开发者 https://www.devze.com 2023-02-13 18:59 出处:网络
I have an xml file like this: <?xml version=\"1.0\" encoding=\"utf-8\"?> <EffectFile> <Effects>

I have an xml file like this:

<?xml version="1.0" encoding="utf-8"?>
<EffectFile>
  <Effects>
    <Effect>
      <Type>Blur</Type>
    </Effect>
   开发者_Go百科 <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.


Just use Any() :

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

精彩评论

暂无评论...
验证码 换一张
取 消