2012-09-06 4 views
0

프로그램은 각 XML 파일의 "File"요소 값을 읽고 그것에 대해 작업합니다. 루트 요소가 "CONFIGURATION"인지 먼저 확인하는 if 문이 필요합니다 (프로그램에서 읽고있는 올바른 XML인지 여부를 확인하는 방법입니다). 제 문제는 .Element에 .Any()를 추가 할 수 없다는 것입니다. 그리고 아래의 if 문이 작동하지 않습니다. 변경해야합니다.루트 요소가 있는지 확인하십시오.

if 문 앞에있는 주석을 참조하십시오.

내 코드 : 여기

static void queryData(string xmlFile) 
    { 
     var xdoc = XDocument.Load(xmlFile); 
     var configuration = xdoc.Element("CONFIGURATION"); 

     //The code works except for the if statement that I added. 
     //The debug shows that configuration is null if no "CONFIGURATION" element is found, 
     //therefore it prompts a "NullReferenceException" error. 
     if (configuration == xdoc.Element("CONFIGURATION")) 
     { 
      string sizeMB = configuration.Element("SizeMB").Value; 
      string backupLocation = configuration.Element("BackupLocation").Value; 
      string[] files = null; 

      Console.WriteLine("XML: " + xmlFile); 

      if (configuration.Elements("Files").Any()) 
      { 
       files = configuration.Element("Files").Elements("File").Select(c => c.Value).ToArray(); 
      } 
      else if (configuration.Elements("Folder").Any()) 
      { 
       files = configuration.Elements("Folder").Select(c => c.Value).ToArray(); 
      } 
      StreamWriter sw = new StreamWriter(serviceStat, true); 
      sw.WriteLine("Working! XML File: " + xmlFile); 
      foreach (string file in files) 
      { 
       sw.WriteLine(file); 
      } 
      sw.Close(); 
     } 
     else 
     { 
      StreamWriter sw = new StreamWriter(serviceStat, true); 
      sw.WriteLine("XML Configuration invalid: " + xmlFile); 
      sw.Close(); 
     } 
+1

무엇을 :)처럼 뭔가를 할 수있다!? 나는 투표를 무효화하기 위해 뭔가 잘못 했습니까? – Blackator

+1

올바른 XML을 사용하고 있는지 확인하려면 @Blackator와 별도로이 질문을 왜 왜곡 한 적이 있습니까? 그렇다면 XML 스키마가 더 나은 선택 일 것입니다. – Habib

답변

2

는 않을까요 간단한 널 체크 사용할 수 있습니까?

var configuration = xdoc.Element("CONFIGURATION"); 

    if (configuration != null) 
    { 
      // code... 
    } 
+0

null이 작동했습니다! 감사! 나는 정말로 어리 석다. :) 묻는다 .Elements()와 같은 다른 더 간단한 방법이 있는가? – Blackator

+0

아니요, 요소가 있는지 단순히 확인하는 경우 Null 검사가 가장 좋은 방법입니다. –

1

또는이

if (xdoc.Elements("CONFIGURATION").Any()) 
{ 
} 
관련 문제