检查 Linq to XML 中节点是否存在
我在一个文件夹中循环浏览一系列 XML 文件。它们几乎总是相同的,但有时我会遇到一个不包含其他文件包含的元素的文件。例如,在一个文件中,它将如下所示:
<sb_sbgp>
<itemtitle>French-Canadian</itemtitle>
<itemtype>subscription</itemtype>
<audience>French people</audience>
</sb_sbgp>
但下一个文件可能如下所示:
<sb_sbgp>
<itemtitle>Spanish</itemtitle>
<itemtype>subscription</itemtype>
</sb_sbgp>
我的问题是我不能只提取包含受众元素的那些文件(这将允许我添加一个 where 子句)。理想情况下,如果它不存在,我希望它默认为null。这是我用来尝试完成此操作的查询:
XDocument doc = XDocument.Load(mydoc.xml);
var x = (from node in doc.Descendants("sb_sbgp")
select new
{
title = node.Element("itemtitle").Value,
type = node.Element("itemtype").Value,
audience = string.IsNullOrEmpty(node.Element("sb_sbgp_audience").Value) ? node.Element("sb_sbgp_audience").Value : null
});
我意识到正在测试是否有一个值,而不是一个元素,但我找不到任何可以让我测试该元素是否存在的东西。帮助?
I have a series of XML files I am cycling through in a folder. They are almost always the same, but from time to time I run into a file that does not contain an element the others contain. For example, in one file, it will look like this:
<sb_sbgp>
<itemtitle>French-Canadian</itemtitle>
<itemtype>subscription</itemtype>
<audience>French people</audience>
</sb_sbgp>
but the next file may look like this:
<sb_sbgp>
<itemtitle>Spanish</itemtitle>
<itemtype>subscription</itemtype>
</sb_sbgp>
my problem is that I can't just pull in those files that contain the audience element (which would allow me to add a where clause). Ideally, I would want it to default to null if it doesn't exist. Here is the query I'm using to try and accomplish this:
XDocument doc = XDocument.Load(mydoc.xml);
var x = (from node in doc.Descendants("sb_sbgp")
select new
{
title = node.Element("itemtitle").Value,
type = node.Element("itemtype").Value,
audience = string.IsNullOrEmpty(node.Element("sb_sbgp_audience").Value) ? node.Element("sb_sbgp_audience").Value : null
});
I realize that is testing to see if there is a value, not an element, but I can't find anything that would allow me to test for the existence of the element. Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试...
try...
你很幸运 - 实际上很容易做到这一点:)
不用使用
.Value
,只需 强制转换为string
,LINQ to XML 将执行您想要的操作:如果强制转换 null
XElement
或X属性
引用任何可为 null 的类型(无论是引用类型还是可为 null 的值类型),您都会得到 null 结果。非常方便。唯一的缺点是,如果有一个空元素,您仍然会得到空字符串而不是空引用。如果你真的想避免这种情况,我建议创建一个像这样的扩展方法:
然后你可以使用:
You're in luck - it's actually really easy to do this :)
Instead of using
.Value
, just cast tostring
and LINQ to XML will do what you want:If you cast a null
XElement
orXAttribute
reference to any nullable type (whether a reference type or a nullable value type) you'll get a null result. Very handy.The only downside of this is that if there's an empty element, you'll still get the empty string instead of a null reference. If you really want to avoid this, I suggest creating an extension method like this:
then you can use:
这个怎么样:
How about this:
这个怎么样?
How about this?