I’m using Linq to extract values from some XML. Shown below is a simplified example to show the problem I’m having. The following code works fine on the XML shown below. The problem I have is when the groupBy section is missing. Because when it’s missing Data.Element("groupBy").Element("property) fails because Data.Element("groupBy") will be null. Is it possible to modify my Linq statement to allow it to provide a default or should it be approached in a different way?
var e = (from Data in theXML.Descendants("exportFile")
select new Export
{
OutputFileName = Data.Element("outputFileName") != null ? (string)Data.Element("outputFileName") : "",
GroupByProperty = Data.Element("groupBy").Element("property") != null ? (string)Data.Element("groupBy").Element("property") : ""
}).First();
<exportFile>
<outputFileName>output.xml</outputFileName>
<groupBy>
<property>DeviceId</property>
</groupBy>
</exportFile>
You can already make it slightly nicer than it is using the null coalescing operator. However, to cope with the
groupbyelement being missing is harder:The conversion to string just returns null if the element reference is null.
An alternative would be:
That uses the extension method which allows you to call
Elementson anIEnumerable<XElement>… so that will (lazily) evaluate a sequence of everypropertyelement under agroupByelement underData, then take the first of them if any exist, then apply the string conversion.