Assuming you're trying to avoid picking up anything where there isn't a short name...
var persons = from person in xmlDoc.Descendants("Table")
let shortNameElement = person.Element("SHORTNAME")
where shortNameElement != null && shortNameElement.Value.Contains("123")
select new
{
shortName = person.Element("SHORTNAME").Value,
longName = person.Element("LONGNAME").Value,
address = person.Element("ADDRESS").Value,
Phone = person.Element("PHONE") != null ?
person.Element("PHONE").Value : "",
zip = person.Element("ZIPCODE") != null ?
person.Element("ZIPCODE").Value : "",
};
Alternatively, you can use the null coalescing operator to make all of these a bit simpler:
var emptyElement = new XElement("ignored", "");
var persons = from person in xmlDoc.Descendants("Table")
where (person.Element("SHORTNAME") ?? emptyElement).Value.Contains("123")
select new
{
shortName = person.Element("SHORTNAME").Value,
longName = person.Element("LONGNAME").Value,
address = person.Element("ADDRESS").Value,
Phone = (person.Element("PHONE") ?? emptyElement).Value
zip = (person.Element("ZIPCODE") ?? emptyElement).Value
};
Or alternatively, you could write an extension method:
public static string ValueOrEmpty(this XElement element)
{
return element == null ? "" : element.Value;
}
and then use it like this:
var persons = from person in xmlDoc.Descendants("Table")
where person.Element("SHORTNAME").ValueOrEmpty().Contains("123")
select new
{
shortName = person.Element("SHORTNAME").Value,
longName = person.Element("LONGNAME").Value,
address = person.Element("ADDRESS").Value,
Phone = person.Element("PHONE").ValueOrEmpty(),
zip = person.Element("ZIPCODE").ValueOrEmpty()
};