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

标签 c# xml linq

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

相关文章:

java - 如何使用 JAXB 生成唯一的元素名称或自动递增的元素名称?

c# - 如何将 EF 查询与字典连接起来

c# - 如何返回一天的结果?

javascript - Javascript 验证中的正则表达式

c# - 仅在特定机器上调用 Web 服务时出现 401

c# - 调试日志弄乱了我的代码

c# - 将 c# 代码文件转换为一个 html 文件?

c# - 使用 gzip 密码保护 xml 文件

xml - 如何使用 XSL 转义 XML 内容以将其安全地输出为 JSON?

xml - 是否有更快的方法来检查 LINQ to XML 中的 XML 元素并解析 bool?