开发者

Dealing with a null datetime element within xml using linq

开发者 https://www.devze.com 2022-12-23 04:55 出处:网络
HI I have an example document that looks like <ItemEntry> <PurchaseDate>2010-03-18T20:36:32开发者_高级运维.81108+13:00</PurchaseDate>

HI

I have an example document that looks like

<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>

As you can see there are couple of elements ExpiryDate and RedeemedDate are are empty.

  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.

Any suggestions?

Thank you


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, you can't just use null - you need to use (DateTime?)null because the compiler won't know how to convert null into a DateTime object

So if you want the value to just be a blank (null) this would be the final code:

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

Assuming DateTime is a declared a nullable (DateTime?)

0

精彩评论

暂无评论...
验证码 换一张
取 消