Hi I want to read an XML document but it may have some of the node missing and if so I want to use a defualt value for the missing nodes.
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; }
}
so in the above only alert1 may exist or all the alerts or none of the alerts! I need to use a default Value for any nodes that does not exist!
I thought I could Alert3 =c.Element("Alert3").Value.开发者_开发问答DefaultEmpty("abc") but this doesn't work!
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"
};
And it is fixed. This also works for things like (int?)
, (DateTime?)
via a range of conversion operators defined on the nodes, so it is easier to write and safer re missing data.
精彩评论