如何使用 XElement 检查元素是否存在?
请注意,在此代码中,我尝试在尝试选择 rdfs:range 元素之前检查它是否存在。我这样做是为了避免运行时可能出现空引用异常。
private readonly XNamespace rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
private readonly XNamespace rdfs = "http://www.w3.org/2000/01/rdf-schema#";
private readonly XElement ontology;
public List<MetaProperty> MetaProperties
{
get
{
return (from p in ontology.Elements(rdf + "Property")
select new MetaProperty
{
About = p.Attribute(rdf + "about").Value,
Name = p.Element(rdfs + "label").Value,
Comment = p.Element(rdfs + "comment").Value,
RangeUri = p.Elements(rdfs + "range").Count() == 1 ?
p.Element(rdfs + "range").Attribute(rdf + "resource").Value :
null
}).ToList();
}
}
这有点困扰我,我真正想做的是这样的:
p.HasElements(rdfs + "range") ?
p.Element(rdfs + "range").Attribute(rdf + "resource").Value :
null
但是没有可用的 HasElement(string elementName)
方法。
我想我可以创建一个方法扩展来做到这一点,但我想知道是否已经内置了一些东西,或者是否有其他方法可以做到这一点?
Notice in this code I am trying to check for the existence of the rdfs:range element before trying to select it. I do this to avoid a possible null reference exception at runtime.
private readonly XNamespace rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
private readonly XNamespace rdfs = "http://www.w3.org/2000/01/rdf-schema#";
private readonly XElement ontology;
public List<MetaProperty> MetaProperties
{
get
{
return (from p in ontology.Elements(rdf + "Property")
select new MetaProperty
{
About = p.Attribute(rdf + "about").Value,
Name = p.Element(rdfs + "label").Value,
Comment = p.Element(rdfs + "comment").Value,
RangeUri = p.Elements(rdfs + "range").Count() == 1 ?
p.Element(rdfs + "range").Attribute(rdf + "resource").Value :
null
}).ToList();
}
}
This is kinda bugging me, what I really want to do is something like this:
p.HasElements(rdfs + "range") ?
p.Element(rdfs + "range").Attribute(rdf + "resource").Value :
null
However there is no HasElement(string elementName)
method available.
I guess I could create a method extension to do this, but am wondering if there is something already built in or if there are other ways to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用:
如果没有元素,它将返回
null
。如果有多个匹配元素,它将抛出异常 - 如果不是所需的行为,FirstOrDefault()
将避免这种情况。编辑:根据我的评论,并利用从 XAttribute 到字符串的转换也处理空值:
如果您在很多地方都有相同的东西,您可以编写一个扩展方法来非常轻松地封装它:
所以 RangeUri 位将是:
You can use:
which will return
null
if there are no elements. It will throw an exception if there's more than one matching element -FirstOrDefault()
will avoid this if it's not the desired behaviour.EDIT: As per my comment, and taking advantage of the conversion from XAttribute to string also handling nulls:
If you have the same thing in many places, you could write an extension method to encapsulate that very easily:
So the RangeUri bit would be:
基本相同,但更整洁
Same basic thing, but neater