English 中文(简体)
在Xml使用linq处理一个无效日期因素
原标题:Dealing with a null datetime element within xml using linq

iii

我有一份象样的文件。

<ItemEntry>
<PurchaseDate>2010-03-18T20:36:32.81108+13:00</PurchaseDate>
<StoreGUID>0a0324ad-5f99-486a-a2d0-870bc6991e9f</StoreGUID>
<ExpiryDate />
<CardID>111111</CardID>
<PurchaseAmount>0</PurchaseAmount>
<RedeemedAmount />
<EntryType>1</EntryType>
<RedeemedDate />
<SalesAssistantID>0</SalesAssistantID>
</ItemEntry>

你们可以看到,有两种因素,如假肢和红eem是空的。

  var q = from c in xml.Elements("ItemEntry")
                    select new mdDetail {
                        PurchaseDate = (DateTime)c.Element("PurchaseDate"),
                        StoreGUID = (Guid)c.Element("StoreGUID"),
                        ExpiryDate = (DateTime?)c.Element("ExpiryDate")??DateTime.MinValue,
                        CardID = (int)c.Element("CardID"),
                        PurchaseAmount = (double)c.Element("PurchaseAmount"),
                         RedeemedAmount = (double?)c.Element("RedeemedAmount"),
                        EntryType = (int)c.Element("EntryType"),
                        RedeemedDate = (DateTime?)c.Element("RedeemedDate") ??DateTime.MinValue,
                        SalesAssistantID = (int)c.Element("SalesAssistantID"),



                    }                      
                    ;
            foreach (var item in q)
            {

            }

I am not sure how to deal with the null element value, I have tried ??DateTime.MinValue and ??null however both give me a " String was not recognized as a valid DateTime." error.

任何建议?

谢谢。

最佳回答
ExpiryDate = String.IsNullOrEmpty((string)c.Element("ExpiryDate"))? 
    DateTime.MinValue : DateTime.Parse((string)c.Element("ExpiryDate"))
问题回答

"You could also use null instead of DateTime.MinValue if ExpireyDate is declared to be nullable"

@Gabe, 您只能使用null - 您需要使用(Datetime?)null,因为汇编者获得了如何将null转换成。 物体

因此,如果你想把价值仅仅作为空白(核心)的话,这将是最后法典:

ExpiryDate = String.IsNullOrEmpty(c.Element("ExpiryDate").Value)? 
    (DateTime?)null : DateTime.Parse(c.Element("ExpiryDate").Value)

假定<代码>Datetime 是宣布无效的(Datetime?)。





相关问题
Updating Linq to XML element values concatenation issues

I am trying to write a app.config / web.config error correcting app which will audit our developers applications for incorrect environment settings. I am using Linq to XML to accomplish this and I am ...

Is LINQ to XML s XElement ordered?

When I use LINQ to XML, is the order of the elements and attributes written out to text guaranteed to be the same order as how I added the XElement and XAttribute objects? Similarly, when I read in ...