假設你試圖避免接受什麼那裏不是短名稱...
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 : "",
};
或者,您可以使用空合併運算符,以使所有的這些簡單一點:
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
};
或者,您可以寫一個擴展方法:
public static string ValueOrEmpty(this XElement element)
{
return element == null ? "" : element.Value;
}
,然後用它是這樣的:
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()
};
這是行不通的,因爲元素返回的XElement,而不是一個字符串。 – 2009-10-05 11:31:39
我的不好,在我寫下它的時刻似乎很簡單。 – 2009-10-05 11:36:56