我正在尝试加载一个 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
关于c# - 如果 XDocument 对象中不存在属性,如何设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27668377/