Skip to main content
 首页 » 编程设计

c#之如果 XDocument 对象中不存在属性,如何设置默认值

2024年02月06日14sxdcgaq8080

我正在尝试加载一个 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