XML to LINQ with Checking Null Elements

2019-02-18 06:05发布

问题:

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 parse out their values. Is there anyway 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 the nodes exist on each line. I know I can test to see if the node exists prior to the parsing, but there may be other data that needs parsed to create the AccountingResponse and I want to avoid if statements that only parse a portion of the XML out at a time.

Or perhaps I'm doing this completely wrong and there's a better way!

回答1:

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...)



回答2:

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 those as well.



回答3:

In C# 6.0 you can use monadic Null-conditional operator ?. After applying it in your example it would 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 more here in part titled Null-conditional operators.