2012-09-06 203 views
0

该程序读取每个XML文件的“文件”元素的值并做一些事情。我需要一个if语句,它首先检查根元素是否为“CONFIGURATION”(这是检查程序读取的XML是否正确的方法)。我的问题是你无法将.Any()添加到.Element,只能添加到.Elements。我的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

我同意,为什么这个问题被低估?,除了那个@Blackator,如果你想确保你使用正确的XML,那么XML Schema可能是一个更好的选择 – Habib

回答

2

岂不简单的空检查工作吗?

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

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

null工作!谢谢!我现在真的看起来很愚蠢.. :)只是问,有没有其他更直接的方式,如.Elements()中的.Any()? – Blackator

+0

不,当您只是检查元素是否存在时,空检查是最好的方法。 –

1

或者你也可以做这样的事情:)

if (xdoc.Elements("CONFIGURATION").Any()) 
{ 
}