2010-10-28 52 views
2

嗨 我想读取一个XML文档,但它可能会缺少一些节点,如果需要,我想为缺失的节点使用默认值。Linq读取缺少节点的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”)但这不起作用!

回答

2
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?)这样的东西,通过在节点上定义的一系列转换运算符,因此更容易编写更安全的重新丢失的数据。

+0

在声音听起来不错之前,我从来没有听说过一个空合并算子,并且是一种享受!谢谢 – Adrian 2010-10-28 08:54:04