範例
以下範例,說明將 date 的attribute 取出後,轉成 datetime 的過程。注意 invoice 這個 element 可能沒有date這個attribute
string xml = @" ";
XElement el = XElement.Parse(xml);
string strDate = el.Element("invoice").Attribute("date").Value;
DateTime? date = null;
if (!string.IsNullOrEmpty(strDate))
date = DateTime.Parse(strDate);
Console.WriteLine(date);
這樣一來,程式碼就顯的有些長而不易維護。
因此,在linq to xml 的設計時,有考慮到這一點。
使用強制轉換的範例
string xml = @" ";
XElement el = XElement.Parse(xml);
DateTime? date = (DateTime?) el.Element("invoice").Attribute("date");
Console.WriteLine(date);
注意到可直接使用 DateTime? date = (DateTime?) … 來取得可能為 null 的 attribute。這樣的方法可適用於 element
沒有留言:
張貼留言