簡體   English   中英

如果XDocument對象中不存在屬性的默認值,如何設置

[英]How to set a default value for attribute if it doesn't exist in the XDocument object

我正在嘗試加載xml文件。 我這樣做:

from e in XDocument.Load(stream).Root.Elements("cust")
                            select new Customer
                            {
                                MemeberID = (int)e.Attribute("custid"),
                                CustomerID = (int)e.Attribute("custid"),
                                FirstName = (string)e.Attribute("fname"),
                                LastName = (string)e.Attribute("lname"),
                                ShowsNumber = (int)e.Attribute("count_noshow"),
                                VisitNumber = (int)e.Attribute("count_resos"),
                                Cancellation = (int)e.Attribute("count_cancel"),
                                MobileNumber = (string)e.Element("phone").Attribute("phonenumber")
                            })

即使事情運行良好,但現在我遇到的情況是xml文檔不必具有mobilenuber屬性。 因此,如果xml節點中不存在此手機號碼,我可以為其設置默認值嗎?

非常感謝

不需要屬性:

MobileNumber = (string)e.Element("phone").Attribute("phonenumber") ?? defaultValue

不需要元素:

MobileNumber = e.Element("phone") != null ? (string)e.Element("phone").Attribute("phonenumber") : defaultValue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM