如何处理 LINQ to XML 查询中缺失的节点
以下示例说明了如何在数据丢失时为 LINQ to XML 查询设置默认值:
IEnumerable<Person> persons =
from e in x.Descendants("Person")
select new Person {
Name = e.Value,
Age = (int?)e.Attribute("Age") ?? 21
};
但是,当属性完全丢失时如何处理?例如,如果该节点没有父节点怎么办?
IEnumerable<Person> persons =
from e in x.Descendants("Person")
select new Person {
Name = e.Value,
Age = (int?)e.Attribute("Age") ?? 21
ParentAge = e.Parent.Attribute("Age")
};
The following example illustrates how to set a default value for a LINQ to XML query when data is missing:
IEnumerable<Person> persons =
from e in x.Descendants("Person")
select new Person {
Name = e.Value,
Age = (int?)e.Attribute("Age") ?? 21
};
But how do you handle when an attribute is missing altogether? For example what if the node has no parent node?
IEnumerable<Person> persons =
from e in x.Descendants("Person")
select new Person {
Name = e.Value,
Age = (int?)e.Attribute("Age") ?? 21
ParentAge = e.Parent.Attribute("Age")
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过困难的方式来处理它,通常使用三元条件运算符
:据我所知,在 C# 中没有更短的方法可以做到这一点。
You handle it the hard way, usually with the ternary conditional operator:
To my knowledge, there is no shorter way to do that in C#.
就我而言,我必须检查“Notes”节点是否存在并处理这两种情况,以及文本字符串中的任何撇号(此代码用于创建 MySQL 插入字符串)。如果字符串存在于单引号中,我会将其括起来,并将所有撇号更改为双引号,或者如果节点不存在,则简单地插入 NULL。我无法控制创建 XML 文件的 XML 客户端,而且我实际上有数以万计的文件需要解析,所以这就是我想出的有效方法:
我不知道如何将其正确添加为评论,所以这只是@Frédéric Hamidi 优秀答案的一个补充。这可能对处于我困境的其他人有所帮助。这大大减少了我的解析代码,所以这是一个很好的解决方案。
In my case I had to check to see if a "Notes" node existed or not and handle both cases, as well as any apostrophes in the text strings (this code is used to create MySQL insert strings). I enclose the string if it exists in single quotes and change any apostrophes to doubled, or simply insert a NULL if the node doesn't exist. I have no control over the XML client that creates XML files, and I have literally tens of thousands of them to parse through, so this is what I came up with that works:
I couldn't figure out how to add this properly as a comment, so this is just an adjunct to @Frédéric Hamidi's excellent answer. This may be helpful to other folks in my predicament. This reduces my parsing code by a large amount, so it's a great solution.