c# - Linq 读取缺少节点的 XML 文档

标签 c# linq .net-4.0 linq-to-xml

嗨 我想读取一个 XML 文档,但它可能缺少一些节点,如果是这样,我想为缺少的节点使用默认值。

XDocument xmlDoc = XDocument.Load(Path.Combine(Application.StartupPath, "queues.xml"));
        var q = from c in xmlDoc.Root.Descendants("Queue")
                select new Queue
                {
                    Alert1 =c.Element("Alert1").Value,
                    Alert2 = c.Element("Alert2").Value,
                    Alert3 =c.Element("Alert3").Value
                };

        var queryAsList = new BindingList<Queue>(q.ToList());


    class Queue
{
    public string Alert1 { get; set; }
    public string Alert2 { get; set; }
    public string Alert3 { get; set; }
}

所以在上面只有 alert1 可能存在或所有警报或没有警报!我需要为任何不存在的节点使用默认值!

我以为我可以 Alert3 =c.Element("Alert3").Value.DefaultEmpty("abc") 但这不起作用!

最佳答案

XDocument xmlDoc = XDocument.Load(Path.Combine(Application.StartupPath, "queues.xml"));
var q = from c in xmlDoc.Root.Descendants("Queue")
        select new Queue
        {
            Alert1 = (string)c.Element("Alert1") ?? "default 1",
            Alert2 = (string)c.Element("Alert2") ?? "default 2",
            Alert3 = (string)c.Element("Alert3") ?? "default 3"
        };

而且是固定的。这也适用于诸如 (int?)(DateTime?) 通过在节点上定义的一系列转换运算符,因此编写 丢失数据更安全。

关于c# - Linq 读取缺少节点的 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4041044/

相关文章:

c# - LINQ 加入 2 个列表<T>

c# - Linq - 获取介于下限和上限之间的值

c# - 按值传递接口(interface)成员

unit-testing - 单元测试。 .NET 4.0 中有哪些新技术/工具?

c# - 如何在 Xamarin.Forms 的 NavigationPage.SetTitleView 中调用 XAML 代码?

c# - 缩小 MahApps.Metro 中的 ProgressRing

c# - 在 WinForms 中更新雷达图

linq - 执行 LambdaExpression 的问题

c# - 在文本框中输入字符时显示 div 标签内容?

xml - XSD:根据元素的条件进行选择