How to check for an element with an XElement?

Note that in this code I am trying to check for the presence of an rdfs: range element before trying to select it. I am doing this to rule out a possible exception using NULL 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();
        }
    }

I like it, I really want to do something like this:

p.HasElements(rdfs + "range") ?
    p.Element(rdfs + "range").Attribute(rdf + "resource").Value :
    null

However, there is no method HasElement(string elementName).

I think I could create a method extension for this, but I wonder if there is something already built-in or if there are other ways to do this?

+3
source share
2 answers

Same but neat

return (from p in ontology.Elements(rdf + "Property") 
let xRange = p.Element(rdfs + "range") 
select new MetaProperty 
{ 
    About = p.Attribute(rdf + "about").Value, 
    Name = p.Element(rdfs + "label").Value, 
    Comment = p.Element(rdfs + "comment").Value, 
    RangeUri = xRange == null ? null : xRange.Attribute(rdf + "resource").Value 
}).ToList(); 
+1
source

You can use:

p.Elements(rdfs + "range").SingleOrDefault()

null, . , - FirstOrDefault() , .

EDIT: , XAttribute , :

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 = (string) p.Elements(rdf + "range")
                                            .Attributes(rdf + "resource")
                                            .FirstOrDefault()
                    }).ToList(); 

, , :

public static XAttribute FindAttribute(this XElement element,
    XName subElement, XName attribute)
{
    return element.Elements(subElement).Attributes(attribute).FirstOrDefault();
}

, RangeUri :

RangeUri = (string) p.FindAttribute(rdf + "range", rdf + "resource")
+7

Source: https://habr.com/ru/post/1756907/


All Articles