[英]Linq To Xml Null Checking of attributes
<books>
<book name="Christmas Cheer" price="10" />
<book name="Holiday Season" price="12" />
<book name="Eggnog Fun" price="5" special="Half Off" />
</books>
我想用linq解析它,我很好奇其他人用什么方法處理特殊問題。 我目前的工作方式是:
var books = from book in booksXml.Descendants("book")
let Name = book.Attribute("name") ?? new XAttribute("name", string.Empty)
let Price = book.Attribute("price") ?? new XAttribute("price", 0)
let Special = book.Attribute("special") ?? new XAttribute("special", string.Empty)
select new
{
Name = Name.Value,
Price = Convert.ToInt32(Price.Value),
Special = Special.Value
};
我想知道是否有更好的方法來解決這個問題。
謝謝,
您可以將屬性強制轉換為string
。 如果它不存在,你將得到null
,后續代碼應該檢查null
,否則它將直接返回值。
試試這個:
var books = from book in booksXml.Descendants("book")
select new
{
Name = (string)book.Attribute("name"),
Price = (string)book.Attribute("price"),
Special = (string)book.Attribute("special")
};
如何使用擴展方法封裝缺少的屬性案例:
public static class XmlExtensions
{
public static T AttributeValueOrDefault<T>(this XElement element, string attributeName, T defaultValue)
{
var attribute = element.Attribute(attributeName);
if (attribute != null && attribute.Value != null)
{
return (T)Convert.ChangeType(attribute.Value, typeof(T));
}
return defaultValue;
}
}
請注意,這只有在T
是字符串知道通過IConvertible轉換的類型時才有效。 如果您想支持更多常規轉換案例,您可能還需要查找TypeConverter。 如果類型無法轉換,這將拋出異常。 如果您希望這些情況也返回默認值,則需要執行其他錯誤處理。
在C#6.0中,您可以使用monadic Null-conditional運算符?.
在您的示例中應用它之后,它將如下所示:
var books = from book in booksXml.Descendants("book")
select new
{
Name = book.Attribute("name")?.Value ?? String.Empty,
Price = Convert.ToInt32(book.Attribute("price")?.Value ?? "0"),
Special = book.Attribute("special")?.Value ?? String.Empty
};
您可以在這里閱讀更多部分標題為Null-conditional運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.