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