2010-01-06 2 views
2

나는 내 XML 문서에서 하나의 요소의 값을 선택하는 시간의 악마가 있어요LINQ-To-XML에서 단일 요소를 선택할 수없는 이유는 무엇입니까?

나는 다음을 수행하려고했습니다
<?xml version="1.0" encoding="utf-8" ?> 
<MySettings> 
    <AttachmentsPath>Test</AttachmentsPath> 
    <PendingAttachmentsPath>Test2</PendingAttachmentsPath> 
</MySettings> 

처럼

내 문서 같습니다

XElement mySettings = XElement.Load("MySettings.xml"); 

string AttachmentsPath = (from e in mySettings.Descendants("MySettings") 
           select e.Element("AttachmentsPath")).SingleOrDefault().Value; 

또는

XElement mySettings = XElement.Load("MySettings.xml"); 

    string AttachmentsPath = mySettings.Element("AttachmentsPath").Value; 

그리고이 작품의 없음. 계속받을 수 있습니다 :

Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 33:
x => x.Type); Line 34: Line 35:
AttachmentsPath = (from e in mySettings.Descendants("Settings") Line 36:
select e.Element("AttachmentsPath")).SingleOrDefault().Value; Line 37:

XML 문서에 올바르게로드 된 것을 볼 수 있습니다.

내 XML 문서에서이 단일 설정 값에 액세스하려고 할 때 잘못된 것은 무엇입니까? 어떤 방법으로 적절한 방법입니까?

답변

0

저는 몇 시간 전에 이와 비슷한 것을 다루었습니다. 내가 찾고 있던 요소가 존재하지 않는다는 것이 밝혀졌습니다. 문서에 "설정"이라는 요소가 없을 수도 있습니까?

1

이것은 잘못된 코드입니다. 클래스의 기본값은 null입니다. 기본값이 반환되면 null 참조 예외가 발생합니다.

SingleOrDefault().Value 

모든 둘째, 당신의 두번째 접근 방식은 가능성이 가장 높은 올바르게 XML 파일을로드 할 수 없음을 의미 작동하지 않는 경우, 또는이 XML의 요소 "AttachmentsPath"를 찾을 수 없습니다. "MySettings"으로

XElement mySettings = XElement.Load("MySettings.xml"); 
string AttachmentsPath = mySettings.Element("AttachmentsPath").Value; 
+0

는 null을 반환 할 수 없습니다. 위에서 주어진 XML을 감안할 때. – Godel

+2

@Godel, 요점은 아닙니다.* null을 먼저 검사하지 않고 * SingleOrDefault() *를 호출 한 후에는 속성이나 메서드에 액세스하려고 시도하면 안됩니다. 나쁜 습관 인 모든 코드에서. –

+2

항상 반환해야하는 경우 (null이 아님) Single()을 사용하는 것이 좋습니다. –

3

은 후손 "MySettings"

더 노드 어쩌면 당신이 할 수없는 경우 SingleOrDefault는 null를 돌려 그러나

var AttachmentsPath = (from e in mySettings.Descendants("AttachmentsPath") 
           select e).SingleOrDefault().Value; 

시도라고하지 않는 루트 노드입니다

var AttachmentsPathElement = (from e in mySettings.Descendants("AttachmentsPath") 
           select e).SingleOrDefault(); 

      if(AttachmentsPathElement != null) 
      { 
       AttachmentsPath = AttachmentsPathElement.Value; 
      } 
2

이 방법이 효과적입니다.

string path = mySettings.Element("AttachmentsPath").Value; 
0

왜 XElement에 문서를로드하고 있습니까? 왜 XDocument가 아닌가?

이 작업을 시도 할 수 :

XDocument mySettings = XDocument.Load("MySettings.xml"); 

string AttachmentsPath = mySettings.Root.Element("AttachmentsPath").Value; 
0

이 코드 시험이 길이야에 시도하십시오 그 작업을 잘

XDocument xmlDoc = XDocument.Load(fileName); 

    XElement page = xmlDoc.Descendants("MySettings").FirstOrDefault(); 

    string AttachmentsPath = page.Descendants("AttachmentsPath").First().Value; 

    string PendingAttachmentsPath= page.Descendants("PendingAttachmentsPath").First().Value; 
1

당신은, 당신이해야 할 모든 루트를 지정 거의가되었다 AttachmentPath가 상주하는 요소. 그것 뿐이다

...

string attachmentsPath= mySettings.Root.Element("MySettings") 
       .Elements("AttachmentsPath").SingleOrDefault().Value; 
관련 문제