gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:43:25 26 4
gpt4 key购买 nike

嗨 我想读取一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com