XML to LINQ with Checking Null Elements

后端 未结 3 1235
不知归路
不知归路 2021-01-13 16:21

The situation I am faced with is parsing an XML document into an object using Linq. During the parse I am checking to make sure Elements are not null before proceeding to p

3条回答
  •  悲&欢浪女
    2021-01-13 16:47

    One simple option is to use Elements rather than Element - that will return a zero-length sequence if the element isn't present. So you can use:

    from x in xdoc.Descendants("Root")
    select new AccountingResponse
    {      
        NetCharge = x.Elements("Charges")
                     .Elements("NetCharge")
                     .Select(y => (int) y)
                     .FirstOrDefault(),
        TotalCharge = x.Elements("Charges")
                       .Elements("TotalCharge")
                       .Select(y => (int) y)
                       .FirstOrDefault(),
    }).SingleOrDefault();
    

    (Note that your original code wouldn't compile, as Value is a string whereas 0 is an int...)

提交回复
热议问题