Linq 读取缺少节点的 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") 但这不起作用!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而且它是固定的。通过在节点上定义的一系列转换运算符,这也适用于诸如
(int?)
、(DateTime?)
之类的内容,因此更容易编写和 重新丢失数据更安全。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.