2011-10-15 6 views
0

LINQ 쿼리 반환 널 (null) 결과

결과 그 URL을 가지고있는 객체이다
nodes = data.Descendants(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Results")).Nodes(); 
     System.Collections.Generic.IEnumerable<Result> res = new List<Result>(); 
     if (nodes.Count() > 0) 
     { 
      var results = from uris in nodes 
          select new Result 
     { 
      URL = 
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Url")).Value, 
      Title = 
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Title")).Value, 
      Description = 
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Description")).Value, 
      DateTime = 
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}DateTime")).Value, 
     }; 
      res = results; 
     } 

, 제목, 설명 및 날짜 시간 변수 정의.

이 모든 것이 정상적으로 작동하지만 노드의 '노드'에 설명 요소가 포함되어 있지 않은 경우 (또는 적어도 이것이 무엇을 던지는 것 같아도) 프로그램은 "res = results;" 코드 줄로 '개체 참조가 설정되지 않음 ...'오류가 발생하고 '새 결과 선택'바로 뒤에 전체 섹션이 강조 표시됩니다.

어떻게 수정합니까?

답변

3

가장 간단한 방법은 Value 속성을 사용하는 대신 string으로 캐스팅하는 것입니다. 그렇게하면 Description에 대한 null 참조로 끝납니다.

그러나, 코드도 많은을 할 수 좋네요 :

XNamespace ns = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web"; 

var results = data.Descendants(ns + "Results") 
        .Elements() 
        .Select(x => new Result 
          { 
          URL = (string) x.Element(ns + "Url"), 
          Title = (string) x.Element(ns + "Title"), 
          Description = (string) x.Element(ns + "Description"), 
          DateTime = (string) x.Element(ns + "DateTime") 
          }) 
        .ToList(); 

가 얼마나 더 간단보기? Techiques 사용 : 빈 순서에 ToList()를 호출

  • 는 당신에게 당신이 오직 쿼리를 한 번에 수행 할 수 있습니다 어쨌든
  • 이 방법 목록을 제공; 잠재적으로 각 노드에서 반복 될 Count()을 호출하기 전에 일반적으로 Count() > 0) 대신 Any()을 사용하십시오.하지만 이번에는 목록을 무조건으로 만드는 것이 더 간단합니다.
  • Elements() 메서드를 사용하면 여러 번 전송하지 않고 하위 요소를 가져올 수 있습니다. XNamespace
  • 사용을 문자열에서 암시 적 변환을 (가 아닌 요소 노드가 발생했다면 이전 코드가 예외를 던진 것)
  • XName
+0

문제가 지속됩니다. 노드에서 누락 된 요소가 아닐 수도 있습니다. '세이프 가드'를 추가하기 위해이 글을 다르게 쓸 수있는 방법이 있습니까? – Ryan

+0

@ 라이언 : 대안 코드를 사용해보십시오. 여전히 실패하는 경우, 잠시이지만 완전한 * 프로그램 (XML 포함)을 질문에 편집하여 진행 상황을 볼 수 있습니다. –

+0

코드를 작성하는이 더 좋은 방법은 문제를 피했습니다 .. Jon – Ryan

1

설명을하면 얻을 수있는 +(XNamespace, string) 연산자를 사용 요소가 포함되어 있지 않은 경우이 값을 테스트해야합니다.

((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Description")) 

이 값을 사용하기 전에 null이 아닙니다. 이 코드를 사용해보십시오 :

var results = from uris in nodes let des = ((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Description")) 
         select new Result 
    { 
     URL = ((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Url")).Value, 
     Title = ((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Title")).Value, 
     Description = (des != null) ? des.Value : string.Empty, 
     DateTime = ((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}DateTime")).Value, 
    };