XML for LINQ with zero element validation

The situation I came across is parsing an XML document into an object using Linq. During parsing, I check that the Elements are not null before proceeding with the analysis of their values. Is there a way to simplify this statement?

var variable = (from x in xdoc.Descendants("Root") select new AccountingResponse { NetCharge = x.Element("Charges") != null && x.Element("Charges").Element("NetCharge") != null ? x.Element("Charges").Element("NetCharge").Value : "0", TotalCharge = x.Element("Charges") != null && x.Element("Charges").Element("TotalCharge") != null ? x.Element("Charges").Element("TotalCharge").Value : "0" }).SingleOrDefault(); 

To summarize, I do not want to continue to check if nodes exist in each row. I know that I can check if a node exists before parsing, but there may be other data that needs to be analyzed to create AccountingResponse, and I want to avoid if instructions that process only part of XML at a time

Or maybe I'm doing it completely wrong, and there is a better way!

+4
source share
3 answers

One simple option is to use Elements , not Element -, which will return a sequence of zero length if the element is missing. 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 the source code will not compile since Value is a string, while 0 is int ...)

+6
source

You can replace

 x.Element("nodeName") != null : int.Parse(x.Element("nodeName").Value) : 0 

with

 (int)x.Element("nodeName") 

It works for string , int , double , decimal , bool , uint , DateTime and Nullable of them.

+2
source

In C # 6.0, you can use the monadic Null-conditional ?. Operator ?. After applying it in your example, it will look like this:

 var variable = (from x in xdoc.Descendants("Root") select new { NetCharge = x.Element("Charges")?.Element("NetCharge")?.Value ?? "0", TotalCharge = x.Element("Charges")?.Element("TotalCharge")?.Value ?? "0" }).SingleOrDefault(); 

You can read here in the section "Operators with a null condition".

0
source

All Articles