2010-07-28 4 views
3

이 코드에서 rdfs : range 요소가 있는지 선택하기 전에이를 확인하려고합니다. 런타임시 가능한 null 참조 예외를 피하기 위해이 작업을 수행합니다.XElement를 사용하여 요소가 있는지 확인하는 방법은 무엇입니까?

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

그러나 더 HasElement(string elementName) 방법을 사용할 수 없습니다 :이 좀 보채있다

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(); 
     } 
    } 

, 내가 정말하고 싶은 것은이 같은 것입니다.

나는이 작업을 수행하기 위해 메서드 확장을 만들 수 있다고 생각하지만, 이미 구현 된 무언가가 있는지 궁금해하고 있습니까?

답변

1

동일한 기본 사항이지만 깔끔하지 않음

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(); 
+0

예. 나는 그것을 좋아한다, 나는 그것을 다른 속성에 대해서도 체크하기 위해 사용할 것이라고 생각한다. –

7

당신은 사용할 수 있습니다

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

을에 요소가없는 경우 null을 반환하는. 일치하는 요소가 두 개 이상있는 경우 예외가 발생합니다. FirstOrDefault()은 원하는 동작이 아닌 경우이를 피합니다.

편집 : 내 댓글 및 XAttribute에서 문자열로 변환을 활용 또한 처리 널 (null)에 따라 경찰 : 당신이 많은 장소에서 같은 일을하는 경우

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") 
+0

잘 알고있어서, FirstOrDefault 기능을 잊어 버렸습니다. 내가 볼 수있는 유일한 잠재적 인 문제는 null을 반환 할 것인지 알 수 없기 때문에 .Attribute를 호출 할 수 없다는 것입니다. –

+1

@Paul : 참. 너는 널을 적절하게 받아들이는 자신 만의 확장 메소드'AttributeOrNull'을 작성하고 싶을지도 모른다. 또는,'Elements (rdfs + "range") 속성을 사용할 수있다. (rdf + "resource") FirstOrDefault()' –

관련 문제